TExcelTAD
Home › Julia › Julia Performance Tips

Julia Performance Tips

Julia can be as fast as C, but only if the compiler can figure out the types of your variables. Most performance advice boils down to one idea: help the compiler know types in advance. This lesson covers the most important tips. Timings are described in prose because they vary from machine to machine.

Measure first

Use @time (built in) or @btime from the BenchmarkTools.jl package. The first call of a function includes compilation, so always time a second call:

julia
julia> function sum_squares(n)
           s = 0
           for i in 1:n
               s += i^2
           end
           return s
       end

julia> @time sum_squares(10^7)    # first call: includes compilation
  0.004917 seconds (1.2 k allocations: 60.484 KiB, 98.71% compilation time)

julia> @time sum_squares(10^7)    # second call: the real cost
  0.000002 seconds

julia> using BenchmarkTools

julia> @btime sum_squares(10^7)
  1.583 ns (0 allocations: 0 bytes)

Watch the allocations column: unexpected allocations in a hot loop usually indicate a type problem.

Tip 1: Put code in functions

Code at the top level of a script works with global variables, whose types can change at any time. The compiler can't specialise it. Code inside a function is compiled for the concrete argument types, which is dramatically faster.

julia · try it yourself
# Slow pattern: a loop at global scope over a non-constant global
data = collect(1:1000)
total = 0
for x in data
    global total += x
end
println(total)

# Fast pattern: the same loop inside a function
function total_of(v)
    t = 0
    for x in v
        t += x
    end
    return t
end
println(total_of(data))
500500
500500

Tip 2: Avoid non-constant globals

If a function reads a global variable, it must check that variable's type on every use. Pass values as arguments, or declare the global const:

julia
rate = 0.05                     # slow when read inside functions
const RATE = 0.05               # fast: the type can never change
grow(x) = x * (1 + RATE)

Tip 3: Write type-stable functions

A function is type-stable if the type of its result depends only on the types of its arguments, not on their values. Here unstable returns an Int for negative input and a Float64 otherwise:

julia · try it yourself
unstable(x) = x < 0 ? 0 : sqrt(x)
stable(x) = x < 0 ? zero(float(x)) : sqrt(x)  # always Float64 for real x

println(typeof(unstable(-1)), " ", typeof(unstable(4)))
println(typeof(stable(-1)), " ", typeof(stable(4)))
println(Base.return_types(unstable, (Int,)))
println(Base.return_types(stable, (Int,)))
Int64 Float64
Float64 Float64
Any[Union{Float64, Int64}]
Any[Float64]

The compiler infers Union{Float64, Int64} for unstable, so code calling it must handle both cases. In the REPL, @code_warntype unstable(1) highlights such unions in red. Helpful functions for stability are float(x), zero(x), one(x), oftype(x, y) and eltype(v).

Tip 4: Keep variable types consistent

The same applies inside a function: don't let a variable change type during a loop.

julia · try it yourself
function mean_bad(v)
    s = 0                 # starts as Int, becomes Float64 inside the loop
    for x in v
        s += x
    end
    return s / length(v)
end

function mean_good(v)
    s = zero(eltype(v))   # Float64 when v holds Float64
    for x in v
        s += x
    end
    return s / length(v)
end

v = [1.5, 2.5, 3.5]
println(mean_bad(v), " ", mean_good(v))
println(Base.return_types(mean_good, (Vector{Float64},)))
2.5 2.5
Any[Float64]

Tip 5: Use concrete types in containers and structs

julia · try it yourself
struct SlowPoint
    x::Real            # abstract field type: values are boxed
    y::Real
end

struct FastPoint{T <: Real}
    x::T               # concrete once T is known
    y::T
end

println(isconcretetype(fieldtype(SlowPoint, :x)))
println(isconcretetype(fieldtype(FastPoint{Float64}, :x)))
println(typeof([1.0, 2.0]), " vs ", typeof(Real[1.0, 2.0]))
println(isbitstype(FastPoint{Float64}), " ", isbitstype(SlowPoint))
false
true
Vector{Float64} vs Vector{Real}
true false

A Vector{FastPoint{Float64}} stores the coordinates inline in one contiguous block; a Vector{SlowPoint} stores pointers to separately allocated objects.

Tip 6: Avoid unnecessary allocations

  • Pre-allocate output arrays and fill them in place (out .= ..., functions ending in !).
  • Use @views for slices you only read: sum(@view A[:, 1]).
  • Fuse broadcasts with @. so @. y = a*x + b makes no temporaries.
  • Prefer generators to temporary arrays in reductions: sum(x^2 for x in v).
julia · try it yourself
function scale_into!(out, v, k)
    @inbounds for i in eachindex(out, v)
        out[i] = v[i] * k
    end
    return out
end

v = [1.0, 2.0, 3.0]
buf = similar(v)
scale_into!(buf, v, 10)
println(buf)
A = reshape(1.0:6.0, 2, 3)
println(sum(@view A[2, :]))
[10.0, 20.0, 30.0]
12.0

Tip 7: Loop in column-major order

Julia arrays store columns contiguously, so the first index should change fastest in nested loops: for j in 1:n, i in 1:m with A[i, j]. Accessing memory in order can be several times faster for large matrices.

Summary

Do Avoid
Work inside functions Heavy loops at global scope
const globals or arguments Non-constant globals
Type-stable return values Returning different types from different branches
Concrete field and element types Any, Real, Vector{Any} in hot data
In-place operations, views, fused dots Allocating temporaries in tight loops
Benchmark the second call Judging speed by the first (compiling) call

Test yourself

Why is the first call of a Julia function often slow?

  1. Julia is interpreted on first use
  2. It includes compiling the function for those argument types
  3. The garbage collector runs first
  4. Arrays are copied

Which function is type-stable?

  1. f(x) = x > 0 ? x : "neg"
  2. f(x) = x > 0 ? 1 : 1.0
  3. f(x) = x > 0 ? x : zero(x)
  4. f(x) = x > 0 ? x : nothing

Why is struct P; x::Real; end slower than struct P{T<:Real}; x::T; end?

  1. Real is deprecated
  2. An abstract field type forces values to be boxed and checked at run time
  3. Parametric types skip bounds checks
  4. It isn't slower