.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.

 

Q for should be used instead of foreach to iterate over collections in performance-critical loops.
A True

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:

Wall Clock Time (ms)

Loop

Structure (5,000 strings)

25.003 for LinkedList<string>
0.037 foreach LinkedList<string>
0.039 for ArrayList
0.053 foreach ArrayList
0.019 for List<string>
0.034 foreach List<string>

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.

Try ANTS Performance Profiler for free, and see how much time you save

ANTS Performance Profiler boxshot
  • Identify performance bottlenecks within minutes
  • Fast and responsive – minimal impact on the execution of your program
  • Drill down to the specific lines of code causing inefficiencies
  • Profile any .NET application, including ASP.NET web applications

 

Download ANTS Performance Profiler


Our promise:

14-day, fully supported, free trial.

Typical download and installation in less than 5 min.

 

 

Feedback Form