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

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

    Keep in mind that the for-loop and foreach-loop are not always equivalent. List enumerators will throw an exception if the list changes, but you won't always get that warning with a normal for loop. You might even get a different exception if the list changes at just the wrong time.

    0 讨论(0)
  • 2020-11-22 04:37

    This is ridiculous. There's no compelling reason to ban the for-loop, performance-wise or other.

    See Jon Skeet's blog for a performance benchmark and other arguments.

    0 讨论(0)
  • 2020-11-22 04:37

    It is what you do inside the loop that affects perfomance, not the actual looping construct (assuming your case is non-trivial).

    0 讨论(0)
  • 2020-11-22 04:37

    Whether for is faster than foreach is really besides the point. I seriously doubt that choosing one over the other will make a significant impact on your performance.

    The best way to optimize your application is through profiling of the actual code. That will pinpoint the methods that account for the most work/time. Optimize those first. If performance is still not acceptable, repeat the procedure.

    As a general rule I would recommend to stay away from micro optimizations as they will rarely yield any significant gains. Only exception is when optimizing identified hot paths (i.e. if your profiling identifies a few highly used methods, it may make sense to optimize these extensively).

    0 讨论(0)
  • 2020-11-22 04:37

    for has more simple logic to implement so it's faster than foreach.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题