Performance of ‘for’ vs. ‘foreach’

I saw someone ask if ‘for’ or ‘foreach’ is faster.  I was surprised.  My code is often slow when I first write it, but it’s never something that could have been fixed by a microoptimization like that.  So I wrote this:

In my code, I find that the most important thing for me to focus on is clarity.  Writing clear code gives me the best chance of ever getting correctness, good performance, maintainability, and flexibility for future requirements.

If I try to directly build any of those, the loss of clarity means that I lose in all of them.

Regarding your specific situation, I would write the clearest way possible, then measure the real-world performance of my app, and then optimize where it matters.

It seems elementary to me, and yet I keep seeing folks trying to microoptimize like this.  So I figured sharing the idea on my blog might be valuable to you, my audience.

Comments (12)

  1. Yohan says:

    It would depend on the structure of the collection. Let’s take, for example, a regular linked list with 1,000 nodes.

    With a for loop, each iteration will require the linked list to start from the head node and move to the node requested. So on the 100’s iteration, it will start at the head node and move 99 nodes to the place you need to be. Not very efficient.

    With a foreach, it will stay on your current node, so each iteration will only require one move.

    That’s just my idea, but I agree with your comments. Keeping your code readable and extendable makes all the difference in the world.

  2. foreach performance really sucks, when you delete items within that foreach. 🙁 It doesn’t do an acutal "foreach", it does a reindex, and shuffle. I’ve taken to using for loops that go backwards, to avoid getting caught by that little bug again 🙁

  3. Jaybaz has an interesting discussion going on about the discussion of performance between "FOR" and "FOREACH"….

  4. Jaybaz,

    well, yes – of course clarity is importat. but why should clarity keep one from doing obvious optimizations like this one? it’s not like ‘foreach’ is a source for any more or less clarity than ‘for’.

    if optimization isn’t part of the overall developmment process – and if it turns out one needs to optimizer later – you’ll end up with a hell of an optimization problem.

    of course – optimizing to early isn’t the best thing to do either…


    thomas woelfer

  5. Frans Bouma says:

    Micro-optimizations are in general not a good idea, but if a loop is ran a lot and the loop itself is not small, it can help using for instead of foreach in some occasions, and because it doesn’t matter much in syntaxis, it is an easy way to make sure what you write is not at all slow.

    That said, as a programmer raised with C and assembler, I always use(d) for and i, j and k as in the Kernighan/Ritchie tradition. But lately I moved towards more foreach usage especially since I use a lot of hashtables and using these in for loops is a bit cumbersome but in foreach (over teh values collection) it’s easier to write and you don’t get your feet into a knot when you have nested loops.

  6. Dan Golick says:

    It looks like the commenters are ignoring your post.

    I on the other hand wholly agree with you.

    Our goal in writing code should be to communicate our intent to the next programmer who reads it (which may be ourselves). The compiler will read the crappiest code and happily execute it.

    Once we have written the best code we can then optimize. And always use a profiler to figure out what to optimize. If you think you know where your bottlenecks lie without profiling your wrong!

    I’m constantly surprised by the location of the bottlenecks.

  7. Jeff Atwood says:

    > It seems elementary to me, and yet I keep seeing folks trying to microoptimize like this

    Welcome to what I like to call "The Human Condition."

  8. AT says:

    Hmm ..

    Original question was "if ‘for’ or ‘foreach’ is faster.".

    You did not answer. Instead of giving an answer "I do not know" you started long talk about microoptimizations.

    Regarding performance – you must note that thouse two are not identical!!!

    ArrayList my;

    foreach(E elem in my) { do(elem); }


    for(int i=0;i<my.Length;i++) { do(my[i]);}

    In ‘for’ case you can get ‘ArgumentOutOfRangeException’ in case of concurent modifications (if you will be lucky ;-),

    But in foreach you can expect (also – not guaranted – but it works !) InvalidOperationException.

    The difference is dramatic. If you do something wrong – "foreach" expected to point this out to you, but using "for" can lead to some random errors.

    P.S> If you feel yourself safe with "int[] arr" – think about Array.Resize 😉

    Sad to note – but looks like both ‘foreach’ and ‘for’ can fail in this case 🙁

  9. TechMount says:

    I don’t know what code clarity have to do with optimization of FOR or FOREACH. Anyway, in many applications what you call micro-optimizations is the difference between a useable application and a go-make-yourself-a-cup-of-coffee-before-I-respond application. This micro-optimization can be the difference between scanning 600,000,000 records in a DB on each interaction and just moving to the next record. Get it?

  10. Jeff says:

    The practice of micro-optimization (at least in the context of jaybaz’s post) can best be viewed as worrying about performance hits that small elements of code *might* cause. The reality is the difference between for and foreach is non-existent until you know for a fact there is a performance problem. Focus on performance of data structures and algorithms first, the small stuff last.

    I once had the same argument with another developer. I took jaybaz’s stance. Performance is vital. Developers caring about the cycles that sometimes single lines of code consume will always be important and can’t be disregarded. However, prematurely optimizing code subtracts from the goal of programming: to solve a problem.

    TechMount: In light of this, code clarity is equal between "for" and "foreach," and deciding which performs better is wasted human cycles until you know switching one for the other will help solve a performance problem.

    I don’t want to say a micro-optimization would never fix a major performance problem like you mention, but it does surprise me. I suspect to fix something like that you’d optimize the database or use different semantics in talking to the database. I’d love the specifics if you’re talking about something you’ve worked on instead of a hypothetical.


  11. Dave says:

    Maybe you could answer the original question, as it is a valid one. If there are perf issues with foreach under certain conditions, then it pays to know them so developers can select the best structure for the job, especially in performance-critical work. Your post reads as really condescending.