What is the purpose of @inbounds in Julia?

function sum(A::AbstractArray)
       r = zero(el type(A))
       for i = 1: length(A)
            @inbounds r += A[i]
       return r


Eliminates array bounds checking within expressions.
In the example above the in-range check for referencing element i of array A is skipped to improve performance. My question is, I do not quite understand why is the @inbounds ever needed in the above example?

1 Like

Since it has a getindex. Logically the setup constrains it to be a valid index, but the compiler may or may not figure this out, so an @inbounds can help.

(Incidentally, the above example from the docstring is outdated, now eachindex(A) is the recommended index iterator.)


Wait, does the compiler sometimes figure it out? I just always use @inbounds (where appropriate) because I figured the compiler wasn’t going to figure out that stuff.

For simple for loops, yes, as a general rule the compiler will figure it out.


I use @inbounds super-rarely these days, since 1.2-pre is getting so good about figuring out the simple stuff, and for the complicated access patterns and index calculations I usually prefer to error if I make mistakes.

I think that peppering code with @inbounds by default is becoming less and less advisable.