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

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

    Probably because the classes (e.g. Console) need to be JIT-compiled the first time through. You'll get the best metrics by calling all methods (to JIT them (warm then up)) first, then performing the test.

    As other users have indicated, 4 passes is never going to be enough to to show you the difference.

    Incidentally, the difference in performance between for and foreach will be negligible and the readability benefits of using foreach almost always outweigh any marginal performance benefit.

提交回复
热议问题