Feed Icon  

Contact

  • Bryant Likes
  • Send mail to the author(s) E-mail
  • twitter
  • View Bryant Likes's profile on LinkedIn
  • del.icio.us
Get Microsoft Silverlight
by clicking "Install Microsoft Silverlight" you accept the
Silverlight license agreement

Hosting By

Hot Topics

Tags

Open Source Projects

Archives

Ads

Eric Gunnerson on Loops

Posted in General at Monday, 19 April 2004 02:23 Pacific Daylight Time

Eric Gunnerson on Loops:

So, I would choose the foreach version unless I needed the index.

In fact, I would advocate this position even if for loops are faster, to avoid the sin of premature optimization.

What was funny to me when I read this was that I've always prefered the foreach version because of readability, but I always assumed it was the slowest. I actually assumed option #3 was the fastest. Glad to hear that my favorite method is the preferred one.

Update: Joshua posts how option #3 is actually the fastest and concludes that:

There are two “rules” I would like to propose:

  • Don't be too clever.  Writing loop 3 just because you think it will be faster is too clever.  Avoiding loop 3 just because “the JIT can't optimize it” is also trying to fool the compiler.  Just write the code that does what you want.
  • Measure perf specific to your scenario.  Measure it yourself.

Update(2): Seems like this topic is a hot one. Kevin Ransom asks To foreach or not to foreach and concludes:

[T]here is no performance benefit to be gained by replacing foreach(...) with for(int i; ...).

 

 

Comments are closed.