Why does the second for loop always execute faster than the first one?

前端 未结 8 1229
日久生厌
日久生厌 2021-01-05 11:14

I was trying to figure out if a for loop was faster than a foreach loop and was using the System.Diagnostics classes to time the task. While running the test I noticed that

8条回答
  •  生来不讨喜
    2021-01-05 11:54

    I don't see why everyone here says that for would be faster than foreach in this particular case. For a List, it is (about 2x slower to foreach through a List than to for through a List).

    In fact, the foreach will be slightly faster than the for here. Because foreach on an array essentially compiles to:

    for(int i = 0; i < array.Length; i++) { }
    

    Using .Length as a stop criteria allows the JIT to remove bounds checks on the array access, since it's a special case. Using i < 4 makes the JIT insert extra instructions to check each iteration whether or not i is out of bounds of the array, and throw an exception if that is the case. However, with .Length, it can guarantee you'll never go outside of the array bounds so the bounds checks are redundant, making it faster.

    However, in most loops, the overhead of the loop is insignificant compared to the work done inside.

    The discrepancy you're seeing can only be explained by the JIT I guess.

提交回复
热议问题