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,137
  • 1
  • 12
  • 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
  • 159,022
  • 53
  • 345
  • 499