Using Julia's @inbounds Macro to Remove Array Bounds Checks Safely
Learn how to safely use Julia's @inbounds macro to drop array bounds checks, see a worked sum‑loop example, and verify correctness and performance gains.
28 Aug 2026, 02:14 UTC

When to use @inbounds in Julia
Wrap array indexing expressions (or the whole loop) with @inbounds to tell the compiler that the indices are guaranteed to be within the array’s bounds, which removes runtime bounds checks and can tighten inner loops.
Worked example: summing a vector
Consider a simple sum function:
function sum_no_check(A::AbstractVector)
s = zero(eltype(A))
for i in eachindex(A)
s += A[i]
end
return s
end
With @inbounds applied to the indexing:
function sum_inbounds(A::AbstractVector)
s = zero(eltype(A))
@inbounds for i in eachindex(A)
s += A[i]
end
return s
end
The macro removes the bounds check on A[i] inside the loop.
How the macro works
@inbounds is a source-to-source transformation: it replaces the wrapped expression with a version that omits the call to checkbounds. It only affects the expression it directly encloses; if you have multiple indexing expressions you must wrap each or wrap the whole block.
Limits and common mistakes
- The macro does not change type inference; if the loop allocates or suffers from type instability, removing bounds checks may give little benefit.
- Applying @inbounds only to the loop header (
@inbounds for i in eachindex(A)) still protects the indexing inside, but if you later compute another index likej = i+1; A[j]you must also wrap that expression or extend the @inbounds block. - Incorrect use can lead to silent memory corruption or segmentation faults because no error is raised when an index is out of range.
- Bounds checks are re‑enabled by default; you can globally turn them off with Julia’s
--check-bounds=noflag, but that is unsafe for debugging.
Verifying safety and performance
- Run the kernel with default bounds checking (or start Julia with
--check-bounds=yes) and confirm that noBoundsErroris thrown for your test inputs. - Add defensive assertions in a debug build:
@assert 1 <= i <= length(A)inside the loop or before it. - Measure execution time with
BenchmarkTools:@benched sum_no_check(A)and@benched sum_inbounds(A). Look for a reduction in the median time; the exact speedup depends on the size ofAand the dominance of bounds checking in the loop. - Compare results of the two functions to ensure they are numerically identical.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.