Code
julia
# 1. Type stability + concrete types — the #1 rule
function sum_fast(v::Vector{Float64})
s = 0.0
@inbounds for i in eachindex(v)
s += v[i]
end
s
end
# 2. Avoid allocations: use views instead of slices
M = rand(1000, 1000)
@views col_norms = [norm(M[:, j]) for j in 1:size(M,2)]
# Without @views, M[:,j] copies the column each iteration
# 3. Preallocate output for repeated calls
function mut_dot!(out, a, B)
@inbounds for j in axes(B, 2)
s = zero(eltype(out))
@simd for i in axes(B, 1)
s += a[i] * B[i, j]
end
out[j] = s
end
end
# 4. @simd to vectorize reductions (asserts no dep order)
function sum_simd(v)
s = zero(eltype(v))
@simd for i in eachindex(v)
s += v[i]
end
s
end
# 5. Inspect & benchmark
@code_warntype sum_fast(rand(3))
using BenchmarkTools
@btime sum_fast($v)
@btime sum($v) # compare to built-in