What is the special case with the foreach loop that eliminates bounds checking?

前端 未结 5 935
清酒与你
清酒与你 2020-12-16 07:02

What is the special case with the foreach/for loop that eliminates bounds checking? Also which bounds checking is it?

5条回答
  •  醉梦人生
    2020-12-16 07:20

    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.

提交回复
热议问题