I have read some questions and answers about this problem, like this, this, and this. Most of them say for-each it not slower than for, and even faster in some case.
But I write the following code and the result make me confused.
public ForWithArraylist() {
// TODO Auto-generated constructor stub
for (int i = 0; i < 1000000; i++) {
number.add(i);
}
now = System.currentTimeMillis();
second = 0;
third = 0;
}
public void random() {
for (int i = 0; i < number.size(); i++) {
int j = number.get(i);
//second = j;
}
second = System.currentTimeMillis();
System.out.println(second - now);
}
public void it() {
for (Iterator<Integer> iterator = number.iterator(); iterator.hasNext();) {
int i = iterator.next();
//third = i;
}
third = System.currentTimeMillis();
System.out.println(third - second);
}
public void each() {
for (Integer num : number) {
int i = num;
}
System.out.println(System.currentTimeMillis() - third);
}
I run it on windows(jdk 6), one of the results is:
(The time is for, iterator and for-each respectively). On average, 'for' is faster the other two about 25 ms.
I run it on MacBook, one of the results is:
(The time is for, iterator and for-each respectively). On average, 'for' is the same as for-each or even slower and iterator is slowest.
So could anyone explain it to me?(the ide, or operating system, or something else)
Edit: Thanks for the reminder of weston, I run it on the another windows (jdk 7), and I have the similar result with MacBook.