.NET Challenge – for or foreach?
Posted by Ramani Sandeep on November 2, 2009
for should be used instead of foreach to iterate over collections in performance-critical loops.
foreach uses an enumerator which can sometimes be slower than the simple iteration of a variable in a for loop. Enumerators, such as those contained in the .NET Framework, have both managed heap and virtual function overhead. The amount of overhead depends on the collection used and the version of the .NET Framework. As always, the best way to determine the overhead between techniques is to run a performance test and compare.
To illustrate the performance impact, 10 strings were concatenated 100 times using the techniques outlined below.
Running against .NET Framework 3.5 using an ArrayList, a generic List and a LinkedList with 5,000 strings, the following results were obtained using Ants Performance Profiler 5:
|Wall Clock Time (ms)||Loop||Structure (5,000 strings)|
Except for the LinkedList, the for loop is faster.
The for loop is thought by many developers to be less readable and maintainable than foreach. Using foreach also makes it possible to iterate across anything that’s IEnumerable, allowing for the creation of more general algorithms and the use of "yield" to build custom collections.
It is normally good practice to code for clarity rather than micro-optimization.
Reference : Rad-gate