The standard
for(int i = 0; i < array.Length; i++) {
...
}
loop is the one that allows the JIT to safely remove array bounds checks (whether the index is within [0..length-1])
The foreach
loop over arrays is equivalent to that standard for
loop over arrays.
EDIT:
As Robert Jeppesen points out:
This will be optimized if the array is
local. If the array is accessible from
other locations, bounds checking will
still be performed. Reference: Array Bounds Check Elimination in the CLR
Thanks! Didn't know that myself.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…