Bounds check performance

The SciML Style guide reads that in Julia after ver1.9, bounds check will reduce performance. But I didn’t see others recommended this, there is no performance reducing in my test. I want to know why it is not recommended to use bounds check removal.

Bounds check removal may decrease performance because it usually results in worse effects. To learn more about effects, see the Base.@assume_effects doc string in the manual. There’s some more info in the Base.Compiler.Effects doc string, which is not in the manual and not public.

Worse effects means various compiler optimizations may be inhibited.

Apart from the above issues due to effects, obviously @inbounds is unsafe (may result in crashes, etc.), so it should only be used when clearly worth the risk and reviewer’s effort.

2 Likes

It’s best to write code where bounds-check removal can be inferred, e.g. using eachindex(A), not 1:length(A) (which also has a bug for some code).

But when @inbounds works, and actually is slower without, what’s then the best alternative? I believe for some arrays, e.g. with asserts, you can induce the compiler to eliminate checks, even without @inbounds. It might (or might not in some case?) be as unsafe.