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

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

    The differences in speed in a for- and a foreach-loop are tiny when you're looping through common structures like arrays, lists, etc, and doing a LINQ query over the collection is almost always slightly slower, although it's nicer to write! As the other posters said, go for expressiveness rather than a millisecond of extra performance.

    What hasn't been said so far is that when a foreach loop is compiled, it is optimised by the compiler based on the collection it is iterating over. That means that when you're not sure which loop to use, you should use the foreach loop - it will generate the best loop for you when it gets compiled. It's more readable too.

    Another key advantage with the foreach loop is that if your collection implementation changes (from an int array to a List for example) then your foreach loop won't require any code changes:

    foreach (int i in myCollection)
    

    The above is the same no matter what type your collection is, whereas in your for loop, the following will not build if you changed myCollection from an array to a List:

    for (int i = 0; i < myCollection.Length, i++)
    

提交回复
热议问题