One way to look at foreach as not so bad

Bill Baxter wbaxter at gmail.com
Fri Oct 20 08:30:53 PDT 2006


Ary Manzana wrote:
>> All that's just about plain 'foreach'.  I still can't see a good 
>> justification for foreach_reverse.  Reverse iteration just isn't 
>> common enough to justify a special case like that.
> 
> 
> I finally think Walter is right with foreach_reverse. It will be used 
> mostly with arrays, and the compiler can then optimize the loop.
> 
> Read this: http://www.digitalmars.com/d/faq.html#foreach
> 
> Replace the article with:
> 
> ---
> When should I use a foreach_reverse loop rather than a for?
> 
> By using foreach_reverse, you are letting the compiler decide on the 
> optimization rather than worrying about it yourself. Is it just 
> performance or readability?
> ---
> 
> :)
> 
> Maybe the compiler can't optimize that much. But D is a system's 
> programming language, and then it should do as much effort as possible 
> to optimize the final code.

Hmm.  From that page:
 >> Like register assignment, let the compiler do the optimization.

That's great, but adding foreach_reverse is basically a 'register'-like 
hint to the compiler that isn't smart enough to figure out how to 
optimize this:
   foreach(i; &foo.reverse)

That's fine, though, the 'register' keyword was also useful as a way to 
micro-optimize C code in the old days.  Just kinda goes against the D 
philosophy of the "trust the compiler; the compiler is smarter than you".

--bb



More information about the Digitalmars-d-announce mailing list