3

I've read many time foreach was performing a bit less efficiently than for on arrays (because it need to constructor/use an iterator) and people were advocating to use for loops instead.

I'm a bit surprised about the compiler not optimizing it (aka: converting it to a simple for loop IL code code). The visual studio 2015 compiler does so much for us (C# 6 languages features) why not fixing this "not so well known" wrong usage of foreach?

Serge Profafilecebook
  • 1,165
  • 1
  • 14
  • 32
  • 2
    That doesn't sound right, and I would ask the people advocating against `foreach` to back up their claims, not others here on SO. Where did you read about it? –  Feb 18 '16 at 08:54
  • If there is a measurable performance difference - does it *matter*? Rather than micro-optimizing looping through arrays, I'd usually be questioning the use of arrays in the first place. – Damien_The_Unbeliever Feb 18 '16 at 08:56
  • Possible duplicate of [In .NET, which loop runs faster, 'for' or 'foreach'?](http://stackoverflow.com/questions/365615/in-net-which-loop-runs-faster-for-or-foreach) – HugoRune Feb 18 '16 at 09:24

1 Answers1

4

The claim that foreach performs worse on arrays than for is incorrect. Jon Skeet did a performance comparison of both:

and concluded that for arrays "the compiler emits largely the same code" and that, for his benchmark, "the results are basically the same."

Community
  • 1
  • 1
Heinzi
  • 167,459
  • 57
  • 363
  • 519
  • The mentioned reference only tests part of the problem. The more iterations the loop performes the less prominent is the fact (at least this was the behavior for .NET 4.5 or 4.7; a long time ago), that foreach needs to initialize an enumerator and for doesn't. In case of List (note: IList performed worse) a for was faster than a foreach. Important is that you call the loop about >100(0) times, so it becomes measurable. As said before this was my experience with .NET 4.x. A lot of things changed since then, so it might not be same nowadays. Very important: MEASURE your use case... – Daniel Bişar Jun 29 '23 at 14:18