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

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

    In cases where you work with a collection of objects, foreach is better, but if you increment a number, a for loop is better.

    Note that in the last case, you could do something like:

    foreach (int i in Enumerable.Range(1, 10))...
    

    But it certainly doesn't perform better, it actually has worse performance compared to a for.

提交回复
热议问题