PROPOSAL: Enhanced for each loop iteration control (original) (raw)

Reinier Zwitserloot reinier at zwitserloot.com
Tue Mar 31 06:29:55 PDT 2009


I very much like the enhanced for each loop iteration control. The
advantages are numerous, in my opinion:

  1. intent - if you're looping across an essentially pre-defined set of
    items (which iterators generally give you), the associated keyword is
    'for' and not 'while'.

  2. Fixes some serious annoyances in java such as a lack of a join
    operator, by giving utility methods that you currently don't even get
    on iterators (first() and index() and company).

and a non-issue, again, IMO:

  1. Speed isn't inherent in the foreach construct in the first place.
    That seems to make 'Slow because it requires creating a bunch of
    objects' a very strange argument. The for-each construct is already
    slow in the following myriad, high-impact ways:

3a: Index looping is just an array lookup, but especially for
Collections, every interaction with your iterator causes a check for
throwing ConcurrentModificationException. Slow.

3b: You cannot for-each over an iterator, you must have an iterable.
The iterable has to create an object to fulfill its contract, so we're
already creating objects here. Another one in the mix really doesn't
make a difference then.

In practice, hotspot makes most of these points moot anyway. In my
experience, the JVM can optimize many things that seem slow, but
sometimes cannot optimize a trivial thing that you'd think wouldn't be
a problem. Without a few PhD degrees in hotspot's internals, profiling
is always a good idea. Is there a profile that shows the JVM would
have serious issues with creating a wrapper object? If not, I think it
would be a bad idea to continue this conversation on the presumption
that extended foreach would somehow be much slower than plain foreach.
I doubt that is true.

NB: Yes, labels are an entirely separate namespace.

--Reinier Zwitserloot

On Mar 31, 2009, at 01:46, Stephen Colebourne wrote:

Stefan Schulz wrote:

Frankly, I cannot see a great advantage of: for (Foo foo : fooList : it) { ... } saving two lines of code over: Iterator it = fooList.iterator(); while (it.hasNext()) { Foo foo = it.next(); ... } The former captures the intent of the loop. The latter is all about plumbing.

by adding two wrappers and stuff to the code in the background. The proposal discusses possible optimisations, however I suspect that hohtspot can probably cope with two additional objects being created. Remember, the extra overhead only happens if you add the optional iterator reference. Stephen



More information about the coin-dev mailing list