Subscript array without bounds check?


(Jens Persson) #1

In situations where the programmer needs the efficiency gained by skipping the bounds check of arr[i] (assuming they know for sure that i will always be within bounds of arr, but the optimizer has no way of proving it), is there a way to do eg:

arr[unchecked: i]

?

If not, would it make sense to add a subscript like that to Array and ContiguousArray or is there some other recommended way (without using pointers instead of arrays or doing an unchecked build)?

Perhaps the following will get the element at index i without any overhead (assuming release mode):

arr.withUnsafeBufferPointer { $0[i] }

?


(Steve Canon) #2

Yes, that successfully elides the bounds check: https://swift.godbolt.org/z/Z3DRl4

Or rather, it does on 4.1.x. I'm not entirely sure what's going on on master yet; there's a regression here that should be fixed (https://bugs.swift.org/browse/SR-8773), but I don't know if it's in the stdlib or compiler yet.

Edit: nevermind, I was looking at a with-asserts build. This still works fine with normal builds.