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

前端 未结 5 1029
清酒与你
清酒与你 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:21

    See this for details:

    http://codebetter.com/blogs/david.hayden/archive/2005/02/27/56104.aspx

    Basically, if you have a for loop, and you explicitly refer to IList.Count or Array.Length, the JIT will catch that, and skip the bounds checking. It makes it faster than precomputing the list length.

    foreach on a list or array will do the same thing internally, I believe.

提交回复
热议问题