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

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

    There are very good reasons to prefer foreach loops over for loops. If you can use a foreach loop, your boss is right that you should.

    However, not every iteration is simply going through a list in order one by one. If he is forbidding for, yes that is wrong.

    If I were you, what I would do is turn all of your natural for loops into recursion. That'd teach him, and it's also a good mental exercise for you.

提交回复
热议问题