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

前端 未结 30 1396
抹茶落季
抹茶落季 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条回答
  •  旧时难觅i
    2020-11-22 04:33

    Unless you're in a specific speed optimization process, I would say use whichever method produces the easiest to read and maintain code.

    If an iterator is already setup, like with one of the collection classes, then the foreach is a good easy option. And if it's an integer range you're iterating, then for is probably cleaner.

提交回复
热议问题