We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
Page Index Toggle Pages: 1
foreach (Read 1204 times)
foreach
Sep 25th, 2006, 8:43pm
 
I'm using;
Code:

for(Iterator = collection.iterator(); iterator.hasNext();){

Now I assume that this is an object wrap version of the ever popular "foreach" command for Collections in Java.

I'm aware that there is a "foreach" command that is new to Java but I'm not sure how new it is. i.e. should I avoid using foreach for fear of alienating older Java versions? And does this foreach only work with arrays?
Re: foreach
Reply #1 - Sep 25th, 2006, 9:04pm
 
Oh.

Iterator is actually slower than a normal for statement ?!?
Code:

Vector stuff = new Vector();
int timer = 0;
void setup(){
for(int i = 0; i < 10000; i++){
stuff.add(new Thing());
}
timer = millis();
for(int j = 0; j < 100; j++){
for(int i = 0; i < stuf.size(); i++){
Thing temp = (Thing)stuff.get(i);
temp.plus();
}
}
println("for i:" + (millis() - timer));
timer = millis();
for(int j = 0; j < 100; j++){
for(Iterator iterator = stuff.iterator(); iterator.hasNext();){
Thing temp = (Thing)iterator.next();
temp.plus();
}
}
println("iterator:" + (millis() - timer));
}

class Thing{
int x;
Thing(){
x = 0;
}
void plus(){
x++;
}
}

What the hell is going on here?
Re: foreach
Reply #2 - Sep 25th, 2006, 10:47pm
 
some iterators create and destroy objects obsessively, or you might just be dealing with the overhead of dealing with objects versus array being much faster (arrays have fewer levels of dereferencing than an iterator does at the level of the jvm).

fwiw, this is the reason that 1) we don't use foreach or iterators anywhere in examples or the processing code itself and 2) adding java 1.5's ability to do foreach and the iterator stuff more magically isn't a huge priority.
Re: foreach
Reply #3 - Sep 28th, 2006, 3:50am
 
Oh, wow, that's good to know about. I should think it would only be a big deal if one were dealing with really huge collections, though.
Page Index Toggle Pages: 1