ZetCode

Julia Performance Tutorial

last modified November 18, 2026

Julia is designed to be fast, but speed depends on how code is written. The compiler can generate efficient machine code when it knows the types of the values involved. An allocation is a block of memory reserved for a new value; fewer allocations usually mean less work for the garbage collector, which is the part of the runtime that reclaims unused memory.

This tutorial covers the most common performance habits: keeping functions type-stable, avoiding untyped global variables, preallocating arrays, using fused broadcasting, taking views instead of copies, skipping unnecessary bounds checks, and measuring allocations with @allocated. Every output block below was produced by Julia 1.13.4; timings are intentionally avoided because they change between runs.

Type Stability

A function is type-stable if its return type can be predicted from the types of its arguments alone. When that is true, the compiler emits one specialised machine-code routine. When the return type varies with the values, the compiler must produce slower, generic code.

main.jl
stable(x) = x + 1
unstable(x) = x > 0 ? x : "negative"

println(Base.return_types(stable, (Int,)))
println(Base.return_types(unstable, (Int,)))

Base.return_types asks the compiler which types a function may return for the given argument types. Adding one integer always gives an Int64, so stable is type-stable. The other function returns either an Int64 or a String depending on the sign of x, so its result is the union Union{Int64, String} and the compiler cannot pick one representation. Returning a single type — for instance a Float64 in both branches — fixes this.

$ julia main.jl
Any[Int64]
Any[Union{Int64, String}]

Inspecting Code with @code_warntype

The @code_warntype macro, provided by the InteractiveUtils standard library, shows the inferred type of every value in a function. Types that the compiler could not narrow down are highlighted in the terminal, which makes instability easy to spot.

main.jl
using InteractiveUtils

f(x) = x + 1
@code_warntype f(1)

When this script is run, the report begins with the method signature MethodInstance for f(::Int64) and then shows x::Int64 and Body::Int64. Those concrete types mean the function is fully inferred. Running the same macro on g(x) = x > 0 ? x : "negative" instead shows Body::UNION{INT64, STRING}; upper-case type names in the report signal a type instability. The exact report includes the source file path and line number, so it is described here rather than pasted as a fixed output block — run the snippet to see the full listing on your machine.

Untyped Global Variables

A global variable lives outside any function. If it is not declared const, its type may change later, so the compiler cannot assume a specific type at compile time. Declaring a fixed value with const lets the compiler treat it like a literal.

main.jl
untyped_global = 1.0
f_untyped() = untyped_global + 1

const TYPED_GLOBAL = 1.0
f_typed() = TYPED_GLOBAL + 1

println(Base.return_types(f_untyped, ()))
println(Base.return_types(f_typed, ()))

f_untyped(); f_typed()   # warm up compilation
println(@allocated f_untyped())
println(@allocated f_typed())

The untyped global makes the return type Any, while the const global gives a concrete Float64. The allocation counts confirm the practical effect: the generic version allocates a boxed value, whereas the type-stable one allocates nothing. The warm-up calls before measurement ensure that compilation time is not counted. Prefer passing values as function arguments; when a global is unavoidable, declare it const.

$ julia main.jl
Any[Any]
Any[Float64]
16
0

Preallocation

Appending to a growing array forces Julia to reserve new memory and copy the old contents whenever capacity runs out. Creating the array at its final size first — preallocation — avoids that repeated copying.

main.jl
function growing(n)
    v = Int[]
    for i in 1:n
        push!(v, i)
    end
    return sum(v)
end

function preallocated(n)
    v = Vector{Int}(undef, n)
    for i in 1:n
        v[i] = i
    end
    return sum(v)
end

println(growing(1000))
println(preallocated(1000))

Int[] starts empty and push! repeatedly grows it; Vector{Int}(undef, n) reserves room for all n entries at once, and undef means the slots are not initialised before we fill them. Both functions produce the same sum, so only the memory traffic differs. Each time a growing array runs out of capacity, Julia must reserve a larger block and copy the old contents; preallocation reserves the final size once. Use @allocated on both versions in your own program to see the difference on your machine — the exact byte counts vary with array size and Julia version, so they are not fixed here.

$ julia main.jl
500500
500500

Broadcast Fusion

Broadcasting applies a function element by element, using dots such as sin.(x). Chained broadcasts are fused: Julia combines them into a single loop with one output array instead of creating a temporary array for each step.

main.jl
x = collect(1.0:1000.0)

function unfused(x)
    y = sin.(x)
    z = cos.(y)
    return z
end

fused(x) = cos.(sin.(x))

println(unfused(x) == fused(x))
println(sum(fused(x)))

Both versions produce identical values, as the first line confirms. The unfused version stores the intermediate array y and then computes z, so it allocates twice. The fused expression cos.(sin.(x)) computes both operations in one pass with a single output array. You can measure the byte counts with @allocated; they vary slightly between runs and machines, so the deterministic equality check is shown instead. Fusion is a deliberate Julia feature: dot calls nest naturally, so writing your own temporary variables can make code slower.

$ julia main.jl
true
765.1057288490813

Avoiding Copies with @views

Slicing an array with A[:, j] creates a copy of the selected elements. A view is a lightweight wrapper that refers to the original data without copying it. The @views macro turns every slice in a block into a view.

main.jl
A = collect(reshape(1.0:10000.0, 100, 100))

function sumcols(A)
    total = 0.0
    for j in 1:100
        col = A[:, j]
        total += sum(col)
    end
    return total
end

function sumcols_views(A)
    total = 0.0
    for j in 1:100
        col = @view A[:, j]
        total += sum(col)
    end
    return total
end

sumcols(A); sumcols_views(A)   # warm up

println(@allocated sumcols(A))
println(@allocated sumcols_views(A))
println(sumcols(A) == sumcols_views(A))

The copying version allocates one new column vector on each of the 100 iterations. @view A[:, j] allocates nothing and reads directly from A, and the final line confirms that both functions give the same sum. Writing @views before a whole expression or loop applies the change to all slices at once. Be careful: a view shares its data with the original array, so mutating the view also mutates the source.

$ julia main.jl
92800
0
true

Skipping Bounds Checks with @inbounds

By default Julia checks that every array index is valid. The @inbounds macro removes those checks from the marked block. The saving is small per access but can matter in tight loops whose indices are already known to be safe.

main.jl
function sum_basic(a)
    total = 0
    for i in eachindex(a)
        total += a[i]
    end
    return total
end

function sum_inbounds(a)
    total = 0
    @inbounds for i in eachindex(a)
        total += a[i]
    end
    return total
end

a = collect(1:1000)
println(sum_basic(a))
println(sum_inbounds(a))

eachindex(a) produces valid indices by construction, so dropping the checks here is safe, and both versions return 500500. Use @inbounds only when you can prove that indices stay in range: an invalid index inside such a block can read unrelated memory or corrupt results instead of raising a BoundsError. Correctness always comes before a small speed gain.

$ julia main.jl
500500
500500

Measuring Allocations with @allocated

The @allocated macro returns the number of bytes allocated while its expression runs. Unlike @time, this number is repeatable for a given program and Julia version, which makes it a good way to compare two implementations in a tutorial or a test.

main.jl
make_vector(n) = [i^2 for i in 1:n]
make_vector(10)   # warm up compilation

println(@allocated make_vector(10))
println(@allocated make_vector(100))

The comprehension builds a new vector, so allocating more elements uses more memory: 144 bytes for ten squares and 928 bytes for one hundred. To interpret a number, compare it with another version of the same code rather than looking at it in isolation. For deeper benchmarking use the BenchmarkTools package, which reports medians and accounts for garbage collection more carefully.

$ julia main.jl
144
928

Best Practices for Performance

Start with correct, readable code, then optimise the parts that measurement shows to be slow.

Source

Julia Performance Tips documentation

Julia InteractiveUtils documentation

This tutorial explored type stability, @code_warntype, global variables, preallocation, broadcast fusion, @views, @inbounds and @allocated. Macros, including the ones used throughout this article, are introduced in Julia macros, and the arrays they operate on in Julia arrays. Linear algebra routines benefit from these habits as well; see Julia linear algebra.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Julia tutorials.