I've read that array-bounds checking can slow down hot spots in programs because with each access of the array, an additional instruction must be executed to ensure it is within the bounds of the array.
As a result, sometimes people recommend letting the upper-bound of the for loop be array.Length
because the JIT can see it and optimize out the array-bounds checking (assuming the body only accesses the current loop variable each iteration.
However, this conflicts with the idea to save the length before-hand in a separate int variable as a form of loop hoisting in to an invariant that many recommend to save performance as well.
Assuming the code will be run in release and not from within Visual Studio (so no debugger), which is optimal? Hoisting the upper-bound in to a separate variable or maintaining the array.Length
for the JIT hints? Is array-bounds checking even still being performed in this case?