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

前端 未结 8 1275
日久生厌
日久生厌 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:49

    You should be using the StopWatch to time the behavior.

    Technically the for loop is faster. Foreach calls the MoveNext() method (creating a method stack and other overhead from a call) on the IEnumerable's iterator, when for only has to increment a variable.

提交回复
热议问题