The two implementations have similar runtime and memory use. In Julia, an explicit loop does not carry an inherent performance penalty relative to vectorized syntax.
The same comparison can use a preallocated output vector:
functionsquared_residuals_broadcast!(out, y, fitted) @. out = (y - fitted)^2return outendfunctionsquared_residuals_loop!(out, y, fitted)for i ineachindex(out, y, fitted) out[i] = (y[i] - fitted[i])^2endreturn outendbroadcast_result =similar(y)loop_result =similar(y)squared_residuals_broadcast!(broadcast_result, y, fitted)squared_residuals_loop!(loop_result, y, fitted)@assert broadcast_result ≈ loop_result@btimesquared_residuals_broadcast!($broadcast_result, $y, $fitted);@btimesquared_residuals_loop!($loop_result, $y, $fitted);
With preallocated output, both broadcast and the explicit loop can run without memory allocations.
Profile
Profile samples a running program to identify where it spends time.
usingProfilefunctionlight_calculation(x) total =0.0for _ in1:10 total +=sum(sin, x)endreturn totalendfunctionheavy_calculation(x) total =0.0for _ in1:100 total +=sum(sin, x)endreturn totalendfunctioncombined_calculation(x)returnlight_calculation(x) +heavy_calculation(x)endprofile_input =randn(100_000)combined_calculation(profile_input) # Compile before profiling.Profile.clear()profile_task =@taskcombined_calculation(profile_input)@profilefetch(schedule(profile_task))Profile.print(IOContext(stdout, :color =>false); format =:tree, maxdepth =5, noisefloor =0.0, tasks =UInt(pointer_from_objref(profile_task)),)
Overhead ╎ [+additional indent] Count File:Line Function
=========================================================
╎52 …h_performance_tips.qmd:156 (::Main.Notebook.var"#2#3")()
╎ 52 …h_performance_tips.qmd:149 combined_calculation(x::Vector{Float64})
╎ 46 …h_performance_tips.qmd:143 heavy_calculation
╎ 46 @Base/reducedim.jl:980 sum
╎ 46 @Base/reducedim.jl:980 #sum#736
╎ 46 @Base/reducedim.jl:984 _sum
╎ 6 …h_performance_tips.qmd:135 light_calculation
╎ 6 @Base/reducedim.jl:980 sum
╎ 6 @Base/reducedim.jl:980 #sum#736
╎ 6 @Base/reducedim.jl:984 _sum
Total snapshots: 55. Utilization: 100% across all threads and tasks. Use the `groupby` kwarg to break down by thread and/or task.
Each count is the number of snapshots in which the function was active, not an exact timing; larger counts indicate likely bottlenecks.
How Julia Executes Code
Julia usually generates specialized machine code when a function is first called with a new combination of argument types.
For example, these two calls use different argument types:
f(x) = x +1f(1) # First call with an Int64f(1.0) # First call with a Float64
2.0
The process is:
A function is called with concrete argument types.
Julia infers the types of intermediate values inside the function.
Julia generates machine code specialized for those argument types.
Later calls with the same argument types reuse the compiled code.
This specialization is one reason why Julia can execute numerical code quickly.
Writing type-stable functions helps Julia generate efficient machine code.
This idea corresponds to Rules 1 and 2.
Rules for high performance
Rule 1: Put performance-critical code in functions
Put numerical loops in functions and pass their inputs as arguments.
A non-constant global can change type, which makes optimization difficult.
performance_data =rand(100_000)functionsum_from_global() total =0.0for value in performance_data total += valueendreturn totalendfunctionsum_from_argument(data) total =0.0for value in data total += valueendreturn totalend@assertsum_from_global() ≈sum_from_argument(performance_data)@btimesum_from_global();@btimesum_from_argument($performance_data);
Type-unstable function
Arguments
x::Float64
Body::Union{Float64, Int64}
Type-stable function
Arguments
x::Float64
Body::Float64
Arguments shows that both functions receive x::Float64.
Body shows the inferred return type:
Union{Float64, Int64} means that the return type is not concrete.
Float64 means that Julia inferred one concrete return type.
Types after :: show Julia’s inference for intermediate values.
Focus on unexpected Any or Union types in performance-critical code.
Use @btime to confirm that the type instability affects performance.
How to write type-stable code
Give each function one return contract.
For example, use separate mean_moment(contributions) and moment_contributions(contributions) functions instead of one function that returns either a scalar or a vector.
Initialize accumulators from the input type.
For example, use total = zero(eltype(values)) instead of total = 0.
Match numeric literals to existing values.
For example, use zero(x) and one(x) instead of 0 and 1.
Convert or extract dynamic inputs once, then pass concrete values to a kernel function.
For example, extract y = df.y and pass y to mse_kernel(y, fitted).
Do not add argument type annotations only for performance.
For example, Julia specializes f(x) when it is called with a Float64; writing f(x::Float64) is not faster for that call.
Rule 3: Reduce allocations inside repeatedly called functions
Allocations are not inherently bad, but repeated allocations increase garbage collection.
If a function repeatedly produces an array of the same size, preallocate the output and reuse it.
If a function returns only a scalar summary, accumulate the scalar directly instead of creating temporary arrays.
functionresiduals_allocating(y, fitted)return y .- fittedendfunctionresiduals!(out, y, fitted) @. out = y - fittedreturn outendresidual_buffer =similar(y)@assertresiduals_allocating(y, fitted) ≈residuals!(residual_buffer, y, fitted)@btimeresiduals_allocating($y, $fitted);@btimeresiduals!($residual_buffer, $y, $fitted);
residuals_allocating creates a new vector each time it is called.
residuals! reuses residual_buffer. By convention, a function ending in ! may modify one of its arguments.
Use @btime to compare allocations before and after the change.
Other tips
Julia’s dense arrays store matrices in column-major order.
In nested loops, vary the row index in the inner loop and the column index in the outer loop. This accesses the matrix one column at a time.
functionsum_column_major(A) total =zero(eltype(A))for j inaxes(A, 2)for i inaxes(A, 1) total += A[i, j]endendreturn totalend
Use the backslash operator (\) to solve linear systems and least-squares problems.
For dense numerical arrays, it uses optimized factorization routines and avoids explicitly computing a matrix inverse.
usingLinearAlgebrabeta_hat = X \ ymul!(fitted, X, beta_hat)
Checklist
Put performance-critical code in functions.
Write type-stable code.
Reduce allocations inside repeatedly called functions.
Applying these rules with AI
Ask AI to read these rules before it writes performance-critical code.
When asking AI to revise code, use prompts such as:
“I want to speed up this function. Diagnose the bottlenecks and rank them by their contribution to runtime. Explain each proposed fix. Distinguish implementation changes from changes to the computational logic.”
“Implement suggestions X, Y, and Z one at a time. After each change, verify that the outputs match the original function for at least 10 sufficiently varied inputs.”