Julia Best Practices for Faster Code (2026)
The fastest Julia code usually comes from a small set of structural habits, not from chasing compiler internals. A module-level Dict without const, an abstract container element type, or a copied slice can force boxing, dynamic dispatch, and allocations that dominate the loop. Fix the structure, then measure again.
That pattern is behind most slow Julia code. Julia 1.13, the current stable line, and 1.10, the long-term support line, both reward the same practices: concrete types, measured changes, and a short verification loop. The julia best practices below are the ones that survive version upgrades because they target how the compiler infers and allocates, not a single release note.
Reproducible Benchmarks and Build Logs
This guide has a runnable companion repository: aguzmans/julia-benchmarks-examples. It contains the benchmark harness, correctness tests, the raw CSV, and the same examples used below. Clone it and run julia --project=. --threads=4 scripts/run_benchmarks.jl; use four threads for a direct comparison, or adjust the count to your machine and record it with the results.
The CI matrix builds the package and runs its tests on Julia 1.10 (LTS) and 1.13 (current stable). The latest successful run is public: build and test log. Exact patch versions are recorded in that log and in results/results.csv; the ratios are more useful than the absolute times, which depend on the machine.
| Julia line | Role | What the repo checks |
|---|---|---|
| 1.10 | Long-term support | Package build, tests, and benchmark harness |
| 1.13 | Current stable | Package build, tests, and benchmark harness |
If you maintain an application rather than a package, use the same split: pin the major line in Project.toml, run the tests on that line, and treat the benchmark as a trend check rather than a fixed number. The point is not the absolute numbers; it is to make each structural change testable before you apply it to production code.
Measure Before You Optimize
Start from a data structure you would actually ship. The example below models ledger entries and sums them, which is the shape of most hot loops in analytics and billing code.
using BenchmarkTools
struct LedgerEntry
account_id::Int32
amount_cents::Int64
posted_at::Float64 # unix timestamp
end
function net_balance(entries::Vector{LedgerEntry})
total = 0.0
for e in entries
total += e.amount_cents
end
return total
end
entries = [LedgerEntry(Int32(i % 500), rand(-5_000:5_000), 1.72e9 + i) for i in 1:100_000]
@time net_balance(entries) # first call: includes JIT compilation, discard this number
@time net_balance(entries) # second call: steady state, 0 allocations expected
@btime net_balance($entries) # min time over many samples; numbers vary by machine
Two details in that output matter. The first @time is dominated by compilation, so no measurement you report should come from it. @btime runs many samples and reports the minimum by default, which is far more stable than a single @time on a laptop with a browser open, as the BenchmarkTools.jl documentation describes.
The $entries interpolation is not cosmetic. Without it, BenchmarkTools evaluates the expression in global scope, the compiler cannot infer the argument type, and you end up benchmarking dynamic dispatch instead of your algorithm. Benchmarks taken that way look 10x to 50x worse than the production path and send people off rewriting loops that were already fine.
Key Takeaways:
- Benchmark with
@btimeand interpolate arguments with$, or you are measuring global-scope dispatch.- Type instability boxes values on the heap; confirm it with
@code_warntypeor@inferredbefore rewriting anything.- Non-const globals, copying slices, and abstract element types cause most production allocations.
- Threads help only when each task writes to private memory; adjacent per-thread counters cause false sharing.
- Julia 1.13 targets precompilation and startup latency; custom system-image builds need a separate memory check.
- mimalloc is not Julia’s default allocator; custom allocator preloading is an experiment and has been reported to crash Julia on exit.
Type Stability Is the Biggest Single Lever
A function is type stable when the compiler can derive a concrete return type from concrete argument types. When it cannot, Julia boxes the value: it allocates a wrapper on the heap and resolves the type at runtime on every access.
abstract type PaymentEvent end
struct CardCharge <: PaymentEvent
amount_cents::Int64
end
struct Refund <: PaymentEvent
amount_cents::Int64
end
# Unstable: Vector{PaymentEvent} erases the concrete element type
function total_untyped(events::Vector{PaymentEvent})
total = 0
for e in events
total += e.amount_cents # field access resolved at runtime
end
return total
end
# Stable: the compiler sees the concrete struct
function total_typed(events::Vector{Refund})
total = 0
for e in events
total += e.amount_cents
end
return total
end
payment_events = PaymentEvent[CardCharge(2_500), Refund(400), CardCharge(9_900)]
refunds = Refund[Refund(400), Refund(1_200)]
@code_warntype total_untyped(payment_events) # body shows the abstract field access and unstable accumulator
@inferred total_typed(refunds) # returns Int64, raises nothing
# Note: @code_warntype output is version-specific; re-read it after each Julia upgrade
@code_warntype prints lowered code with inferred types and marks unstable slots in red in a color terminal. @inferred is the assertion form: it throws when inference fails, so it belongs in your test suite next to the correctness tests. Across a whole package rather than one call, JET.jl reports inference failures and possible method errors statically, without waiting for a benchmark run to trip over them.
The fix for the unstable version is not a type annotation on the loop variable. Change the container instead: keep Vector{CardCharge} and Vector{Refund} separate, or switch to a struct-of-vectors layout, or wrap the per-type work in a function barrier so the inner function receives a concrete vector. The Performance Tips chapter of the Julia manual covers the same rules from the compiler's point of view and is worth a re-read after each minor release.
Allocations: Globals, Views, and Function Barriers
Most heap allocations are GC-visible objects, and inside a tight loop the allocation cost can beat the arithmetic cost. Non-const globals, slicing that copies, and closures capturing mutable state account for most of what appears in a real profile.
# Slow: a non-const global lets the compiler lose the concrete type
exchange_rates = Dict{Symbol, Float64}(:usd => 1.0, :eur => 1.087, :gbp => 1.271)
convert_to_usd(amount, currency) = amount * exchange_rates[currency]
# Fast: const binding plus a concrete signature
const EXCHANGE_RATES = Dict{Symbol, Float64}(:usd => 1.0, :eur => 1.087, :gbp => 1.271)
convert_to_usd_fast(amount::Float64, currency::Symbol) = amount * EXCHANGE_RATES[currency]
sensor_matrix = rand(4_000, 64) # 4k sensors, 64 readings each
# Copying slices: each row slice allocates a new Vector
row_means_copy(m::Matrix{Float64}) =
[sum(m[i, :]) / size(m, 2) for i in axes(m, 1)]
# Views: no copy, though row access on a column-major matrix is strided
row_means_views(m::Matrix{Float64}) =
[sum(@view m[i, :]) / size(m, 2) for i in axes(m, 1)]
@allocated row_means_copy(sensor_matrix) # one Vector per row
@allocated row_means_views(sensor_matrix) # the result Vector and little else
# Note: production code should also assert size(m, 1) > 0 before dividing by columns
The view version is not automatically faster. Julia matrices are column-major, so walking a row is a strided access pattern that wastes cache lines and can block SIMD. If row_means_views is still the bottleneck after the copies are gone, transpose the problem and iterate down columns rather than sprinkling @views everywhere. The CfRR course material on performant Julia makes the same ordering point: excessive allocation traces back to type instability and small temporary arrays, in that order.
Function barriers cover the case where part of your code must stay dynamic, such as a dispatch on a symbol parsed from a config file. Do the dynamic lookup once at the top, then call a function whose arguments are concrete. Everything inside the barrier compiles as if the union type never existed. The Performance Tips chapter's separate-kernel-functions section covers the pattern in more detail.
Threads: --threads=auto and Safe Accumulation
Launch Julia with julia --threads=auto or set JULIA_NUM_THREADS, then confirm the count with Threads.nthreads(). Julia's threading does not make data structures safe. Unsynchronized writes to a shared Dict, push! into a shared vector from several tasks, and closures mutating a captured variable all break under load.
using Base.Threads
# Chunked @spawn: each task owns a private counter and returns it
function count_above_threshold(xs::Vector{Int32}, threshold::Int32; nchunks::Int = 4 * nthreads())
n = length(xs)
chunk = cld(n, nchunks)
tasks = Task[]
for lo in 1:chunk:n
hi = min(lo + chunk - 1, n)
push!(tasks, Threads.@spawn begin
c = 0
@inbounds for i in lo:hi
c += (xs[i] > threshold)
end
c # return value only, no shared write
end)
end
return sum(fetch, tasks)
end
# Race-free but slow at scale: adjacent counters share cache lines
function count_above_threaded(xs::Vector{Int32}, threshold::Int32)
partials = zeros(Int, nthreads())
Threads.@threads :static for i in eachindex(xs)
if xs[i] > threshold
partials[threadid()] += 1
end
end
return sum(partials)
end
The :static schedule carries the guarantee. @threads :static hands each thread one contiguous chunk of the iteration space, so the write to partials[threadid()] is not a data race even without a lock. The default :dynamic schedule does not give you that. What remains is physical: nthreads() counters of 8 bytes sit in one or two 64-byte cache lines, so each core invalidates every other core's line on each increment. That is false sharing, and it can consume the entire speedup.
Padding each counter to a full cache line fixes the @threads version. The chunked @spawn version avoids the problem differently: tasks return their counts, and the reduction runs on one thread, so nothing is shared during the loop. Spawning and scheduling add overhead, so chunking rarely pays off for very short loops; benchmark both versions on the target machine before choosing one.
Time-to-First-Execution with PrecompileTools
Compilation latency is a different problem from throughput, with a different fix. PrecompileTools.jl runs a small representative workload during package precompilation and caches the resulting native code in the pkgimage file, so the first user call skips the compiler.
using PrecompileTools: @setup_workload, @compile_workload
@setup_workload begin
# Data created here is not stored in the precompile file
entries = [LedgerEntry(Int32(i % 500), Int64(100 * i), 1.72e9 + i) for i in 1:1_000]
@compile_workload begin
net_balance(entries)
end
end
To decide what belongs in the workload, run your package with julia --trace-compile=stderr -e 'using LedgerPkg; LedgerPkg.run()' and keep the methods that dominate the output. Hold the workload to the millisecond range. It executes on every precompile, including in CI, so a heavyweight workload trades one latency problem for another.
Julia 1.13 targeted exactly this pain point: faster package precompilation, faster GC marking by skipping image objects, and scheduler and interrupt fixes. One user report in the Julia Discourse release thread described roughly 30% shorter precompilation on Linux and fewer test-triggered recompilations; treat that as a machine-specific report, not a guarantee. For a deploy that rebuilds an environment per container, the precompilation work is still the most useful change in the release.
The trade-off sits in system images. A reported regression, issue #63141, describes system-image builds failing on excessive RAM usage in 1.13, with users noting a fix targeted at 1.14. If your deployment bakes a custom system image, test that step before upgrading.
Version Facts and Allocator Claims
Pin deliberately. Julia 1.13.3 is a patch release: bug fixes, documentation, and performance work, with no new features or breaking changes, per the release announcement. Julia 1.10.12 is the twelfth patch release of the 1.10 LTS series, per the LTS announcement. Services that value stability over the 1.13 latency gains stay on 1.10.12; services that redeploy often and want shorter precompilation move to 1.13.3.
On allocators, the honest answer is that mimalloc is not Julia's default and not a shipped user-facing behavior. Preloading a custom allocator system-wide with LD_PRELOAD has been reported to crash Julia on exit across several versions (issue #61031), and a proposal to consider rpmalloc or mimalloc was discussed in the tracker (issue #56142). Treat allocator swapping as an experiment you measure, not a best practice you adopt.
| Tool | Question it answers | Typical call | Limitation |
|---|---|---|---|
| BenchmarkTools.jl | How long a steady-state call takes | @btime f($x) |
Needs $ interpolation for non-const inputs; reports the minimum by default |
@time / @allocated |
How much memory one call allocates | @allocated f(x) |
The first call includes JIT compilation |
@code_warntype / @inferred |
Whether the compiler can infer the return type | @code_warntype f(x) |
Shows one specialization; @inferred throws instead of reporting |
| Profile + ProfileView | Which functions consume the time | @profile f(x) |
Sampling based, so short workloads give noisy profiles |
| JET.jl | Which methods are type unstable across a package | Static analysis of the module | Reports inference problems, not runtime speed |
The Modern Julia Workflows guide covers the surrounding tooling, including PrecompileAfterUpdate.jl for re-precompiling environments after a version bump, which removes a recurring source of "it got slow again" tickets.
A Pre-Merge Checklist
Run these in order on any performance-sensitive change. Each step costs less time than the one after it.
- Start with
--threads=auto, confirmThreads.nthreads(), and record the count next to your benchmark numbers. - Compare
@allocatedbefore and after the change. Allocation count that does not drop means the rewrite gained nothing. - Run
@code_warntypeon the hot function and look forCore.BoxorUnionin the body. - Add
@inferredassertions to the test suite for every function on the hot path. - Audit module-level bindings for a missing
const; configuration tables are the usual offender. - Benchmark with interpolated arguments and put the minimum time plus allocation count in the pull request.
- If you parallelize, confirm no shared mutable container is written from more than one task.
None of this requires compiler internals. It requires measurement discipline and a handful of structural rules that have held across every 1.x release. The size of the gap depends on the workload, which is exactly why the benchmark comes first.
Updated November 19, 2026: added the companion benchmark repo, the public Julia 1.10/1.13 build log, and a short FAQ. The performance examples remain valid across the 1.x line; check the repo for the exact patch versions and current results.
FAQ: Julia Best Practices
What are the most important Julia best practices?
Use concrete element types, keep globals const or pass them as arguments, benchmark with interpolated inputs, and verify thread safety before parallelizing. Those four changes fix most slow Julia code before compiler flags enter the conversation.
Should I use Julia 1.10 LTS or 1.13?
Choose 1.10 when stability across a long deployment matters. Choose 1.13 when faster precompilation and startup are worth tracking the current stable line. The generic performance advice is the same; test the line you deploy, not whichever version happens to be newest.
Why is my Julia code still slow after adding type annotations?
Annotations do not fix an abstract container type or a non-const global. Check @code_warntype for Union or Core.Box, and compare @allocated before and after. Fix the data layout first.
Is @views always faster?
No. Views avoid copies, but row slices of a column-major matrix remain strided. Measure the operation; sometimes iterating down columns is the larger win.
How do I reproduce the benchmark numbers?
Use the companion repository above. Run it on Julia 1.10 or 1.13 with four threads, keep the CSV, and compare ratios on your own machine. Absolute times from one laptop do not transfer.
Related Reading
More in-depth coverage from this blog on closely related topics:
Sources and References
Sources cited while researching and writing this article:
- GitHub - JuliaCI/BenchmarkTools.jl: A benchmarking framework for the ...
- Performance Tips · The Julia Language
- Performant Code , Home Page - GitHub Pages
- GitHub - JuliaLang/PrecompileTools.jl: Reduce time-to-first-execution ...
- Congrats for Julia 1.13! - Community - Julia Programming Language
- Building a system image using Julia 1.13 fails (due to excessive RAM usage) · Issue #63141 · JuliaLang/julia · GitHub
- Julia 1.13.3 has been released - Announcements - Julia Programming Language
- Julia v1.10.12 has been released - Announcements - Julia Programming Language
- [BUG] Julia crashes on exit (SIGABRT/SIGSEGV) when custom ... - GitHub
- Consider rpmalloc and/or mimalloc · Issue #56142 · JuliaLang/julia
- Optimizing your code - Modern Julia Workflows
- Companion benchmark repository
- Public build and test log for Julia 1.10 and 1.13
Rafael
Born with the collective knowledge of the internet and the writing style of nobody in particular. Still learning what "touching grass" means. I am Just Rafael...
