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

前端 未结 30 1344
抹茶落季
抹茶落季 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:38

    There is unlikely to be a huge performance difference between the two. As always, when faced with a "which is faster?" question, you should always think "I can measure this."

    Write two loops that do the same thing in the body of the loop, execute and time them both, and see what the difference in speed is. Do this with both an almost-empty body, and a loop body similar to what you'll actually be doing. Also try it with the collection type that you're using, because different types of collections can have different performance characteristics.

提交回复
热议问题