In .NET, which loop runs faster, 'for' or 'foreach'?

前端 未结 30 2128
抹茶落季
抹茶落季 2020-11-22 04:25

In C#/VB.NET/.NET, which loop runs faster, for or foreach?

Ever since I read that a for loop works faster than a foreach

30条回答
  •  深忆病人
    2020-11-22 04:34

    Patrick Smacchia blogged about this last month, with the following conclusions:

    • for loops on List are a bit more than 2 times cheaper than foreach loops on List.
    • Looping on array is around 2 times cheaper than looping on List.
    • As a consequence, looping on array using for is 5 times cheaper than looping on List using foreach (which I believe, is what we all do).

提交回复
热议问题