foreach is slower than for?

Jonathan M Davis jmdavisprog at gmail.com
Thu Sep 9 16:19:44 PDT 2010


On Thursday, September 09, 2010 13:31:13 Stanislav Blinov wrote:
> Justin Johansson wrote:
> > On 9/09/2010 6:56 AM, Tomek Sowiński wrote:
> >>> Without -O -release the difference is even greater
> >>> 
> >>> Is this normal? I mean, shouldn't the compiler optimize foreach a bit
> >>> more? Or is it that I simply misunderstand generated code?
> >> 
> >> Yes, it should; that was the point of having foreach in the language:
> >> http://www.d-programming-language.org/faq.html#foreach
> >> 
> >> I think it's just that there's always plenty of more urgent things with
> >> DMD.
> >> 
> >> 
> >> Tomek
> > 
> > Is there a roadmap for what things are more urgent?  The OP has a
> > valid point in asking what is the point of the language.  A decent
> > roadmap would help newcomers and oldcomers alike to stay with the
> > Holy Grail of D.
> > 
> > Justin
> 
> Well, I actually didn't ask 'what's the point of foreach is if it's
> slower' :) I just wanted to find out if it's really as far as it can
> get, or is it simply not polished yet.
> 
> Nevertheless, I agree that seeing some kind of roadmap would be nice,
> especially now when D2 is shaped to certain extent and someone would
> consider starting mean projects with it.

I don't know about the case with arrays, but if foreach is using opApply(), it 
uses a delegate, which is definitely going to be less efficient. Theoretically, 
opApply and its delegate could be inlined to replace the foreach and definitely 
improve that efficiency (especially because that particular delegate will never be 
called anywhere else), but that's not currently done. So, there are definitely 
things that can (and likely eventually will) be done to improve the efficiency of 
foreach as well as other basic stuff, but as said in another post, other stuff has 
higher priority.

- Jonathan M Davis


More information about the Digitalmars-d mailing list