Home of the AlmostImplementedException

For vs Foreach

Sometimes, especially with C# you hear alot of “common knowledge” about performance and developers mistakes. As an (bad) example I want to refer to 8 Most common mistakes C# developers make and in particular point 7 “using foreach instead of for”.

So whats wrong with this kind of post? First of all, it refers to another post from 2004 (!) to indicate that foreach is slower then for.
That are roughly 9 years and thats like an eternity in software development.
But more important, it uses the wrong perspective. The worst you can do is to improve code to get it faster and no other developer can understand it anymore.
The main difference between a good (experienced) and a bad (or newbie) developer is the readability of his or her code!

So whats the difference between for and foreach?
For gives you a counter you can work with and most times working with arrays you’ll need it. So use for.
If you just need the values of a list or an array, use foreach! Its easier to read for others and believe me, for you too.

But whats about the performance? Would others laugh at me if i use foreach and tell me its slow? Maybe they do, but prove them wrong!

With older .Net versions foreach was “belived to be” about 5 times slower then for (see the link at the end of this post). Since at least .Net 4 there are no big differences.
But whats more important, what does 5 times slower mean? Sounds like alot. Is the execution time of the a foreach-loop 5 times slower then the for-loop? NO! it isn’t.
Only the head of the loop took more time, but the slowest part of a loop is the code we looping through and not the head.
The executiontime of an empty loop with even a million iterations is below 1ms.
If you want or need to improve the performance look at the code inside your loop!

And here a few advices i want to get rid of ;-):
– Don’t belive everything you read about bad/good practice
– Don’t improve code unless you have to. (never change a running system)
– Write your code as clean as you can – make it easy to read
– If you have to improve the performance look at the right places and measure it with release-code (not debug!)

And here is the other post about the performance of for and foreach. Its wrong by the way (read the comments below the post to see why).

Share :

Leave a Reply

Your email address will not be published. Required fields are marked *