Freigeben über


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

  • Anonymous
    December 23, 2004
    The comment has been removed
  • Anonymous
    December 23, 2004
    The comment has been removed
  • Anonymous
    December 23, 2004
    Jaybaz has an interesting discussion going on about the discussion of performance between "FOR" and "FOREACH"....
  • Anonymous
    December 23, 2004
    The comment has been removed
  • Anonymous
    December 23, 2004
    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.
  • Anonymous
    December 23, 2004
    TrackBack From:http://www.cnblogs.com/jme/archive/2004/12/24/81591.html
  • Anonymous
    December 23, 2004
    The comment has been removed
  • Anonymous
    December 24, 2004
    > 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."
  • Anonymous
    December 24, 2004
    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); }
    vs.
    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 :-(
  • Anonymous
    December 26, 2004
    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?
  • Anonymous
    January 04, 2005
    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.

    thanks!
  • Anonymous
    January 09, 2005
    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.