for versus foreach

kris foo at bar.com
Sat Apr 8 12:49:52 PDT 2006


Ameer Armaly wrote:
> What are the reasons/differences in using foreach over a for loop?  Is 
> it just performance or readability?

Both.

Foreach is syntactically succinct, and can often produce better codegen 
than either integer-based or pointer-based for() loops ~ I did quite a 
bit of testing in this arena when writing high-throughput UTF 
converters, and was vaguely surprised by the subtle but noticable 
differences. This is perhaps most visible when iterating across arrays, 
where conventional wisdom might have favoured a pointer-based for() instead:

int[] xx;

foreach (x; xx)
	 ...

With the x86-32 architecture, anything that prevents register-spills is 
a bonus for some types of code, and I found foreach to be a better 
choice in a number of cases. The potentially negative aspect is that 
foreach is based upon a callback mechanism, so if the loop-body cannot 
be "inlined" there will be a call/ret involved for each iteration. 
Whether or not that's significant is very much application specific.

 From a syntactic perspective, you can get quite creative with foreach. 
Yet even the typical fare is quite elegant:

foreach (record; table.iterator)
	{
	record.set ("fu", "bar");
	...
	record.update;
         }


One syntactic benefit of for() loops is that one can declare and 
initialize control-vars within:

for (int i=0, j=foo.length; i < j; ++i)
      ...

Whereas foreach() tends to encapsulate such things within the opApply() 
design. Both approaches are very useful; foreach is perhaps the "more 
elegant" choice for many cases ~ perhaps the majority? The nice thing 
about foreach() is that the opApply() involved is encapsulated by the 
hosting class/struct ~ this has all the OOP benefits in terms of 
isolating implementation details that might otherwise have to be exposed 
at each traditional for() site. Yes, one can design in such a way that 
for() does something similar in terms of encapsulation; but it's not 
quite the same.

For reference purposes, I think there's only a few for() loops within 
Mango, whereas there's lots of foreach() ~ the former are used, for 
example, to sweep backwards over an array; foreach doesn't currently 
handle that effectively.



More information about the Digitalmars-d-learn mailing list