Performance Tips: @inbounds, @fastmath, views
Write Julia that runs at C speed by removing bounds checks, avoiding allocations, and using views.
Code
# 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-inExplanation
Julia's speed comes from type inference generating specialized native code. Three tools unlock near-C performance: @inbounds removes bounds checks (use only when certain), @simd lets the compiler vectorize associative reductions, and @views turns slices into zero-copy views. Preallocating outputs with bang-style functions (mut_dot!) avoids GC pressure in hot loops. Always benchmark with @btime from BenchmarkTools — not @time, which includes compilation.
More Julia Snippets
Broadcasting & Vectorization
Apply a function element-wise over arrays with dot syntax and @.
Multiple Dispatch
Select methods by the runtime types of all arguments, not just the receiver.
Parametric Types & Performance
Define generic, type-stable containers that compile to specialized code.
Macros & Expressions
Manipulate Julia syntax trees as first-class data via :expr and macro.
Multi-threading & Distributed Compute
Parallelize loops with @threads and offload tasks with @spawn / pmap.
DataFrame Operations (DataFrames.jl)
Filter, transform, group, and join tabular data with DataFrames.jl.