.NET Challenge – for or foreach?
Brendan Tompkins
Co-Founder of CodeBetter.com "Use line-level profiling to drill down to the specific lines of code responsible for performance inefficiencies. Save yourself hours of time blindly chasing performance issues. Give ANTS Performance Profiler a try." Try ANTS Performance Profiler and see how much time you will save. Free 14-day trial.
|
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. View more... 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:
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. Try ANTS Performance Profiler for free, and see how much time you save
|





