Skip to content
Julia

Performance Tips: @inbounds, @fastmath, views

Write Julia that runs at C speed by removing bounds checks, avoiding allocations, and using views.

By EZ4Code Team
performanceoptimizationsimd

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-in

Explanation

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