@inbounds not working?

Simply tried the following:

a=[0.5]
@inbounds b=a[2]

yielding surprisingly

BoundsError: attempt to access 1-element Vector{Float64} at index [2]

Stacktrace:
 [1] getindex(A::Vector{Float64}, i1::Int64)
   @ Base .\array.jl:805
 [2] top-level scope
   @ In[9]:2
 [3] eval
   @ .\boot.jl:360 [inlined]
 [4] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
   @ Base .\loading.jl:1116

Have I missed some basic point?

May be because you’re working in the global scope?

julia> function ff()
       a = [0.5]
       @inbounds b = a[2]
       end
ff (generic function with 1 method)

julia> ff()
1.32235279e-315
3 Likes

It is somewhat more subtle than that:

julia> x = [1]
1-element Vector{Int64}:
 1

julia> let a = x
           @inbounds b = a[2]
       end
ERROR: BoundsError: attempt to access 1-element Vector{Int64} at index [2]
Stacktrace:
 [1] getindex(A::Vector{Int64}, i1::Int64)
   @ Base ./array.jl:861
 [2] top-level scope
   @ REPL[8]:2

1 Like

To be specific, @inbounds only works inside type-stable compiled contexts with inlining enabled. If you’re not compiled or type-stable, then the overhead from bounds checking is the least of your worries.

8 Likes

It’s worth pointing out that this overhead is pretty negligible in general. The only time it’s likely to make much of a difference is when it prevents SIMD.

6 Likes