## 迭代器和For循环的效率比较

2013年08月31日 ⁄ 综合 ⁄ 共 1425字 ⁄ 字号 评论关闭

```package com.test.arrayList;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class TestArrayList {

private static final int COUNT = 700000;
private static List<Person> persons = new ArrayList<Person>();

public static void main(String args[]) {
init();

System.out.println("For遍历测试：" + testFor() + "微秒");

System.out.println("迭代器遍历测试：" + testIterator() + "微秒");

System.out.println("有人很喜欢的foreach测试：" + testForEach() + "微秒");

}

public static void init() {
Person person = null;
for (int i = 0; i < COUNT; i++) {
person = new Person("第" + i + "个", i, i * 100);
}
}

public static long testIterator() {
long start = System.nanoTime();
Person person = null;
for (Iterator<Person> it = persons.iterator(); it.hasNext();) {
person = it.next();
}
return (System.nanoTime() - start) / (1000);
}

public static long testFor() {
long start = System.nanoTime();
Person person = null;
for (int i = 0; i < persons.size(); i++) {
person = persons.get(i);
}
return (System.nanoTime() - start) / (1000);
}

public static long testForEach() {
long start = System.nanoTime();
Person person = null;
for (Person p : persons) {
person = p;
}
return (System.nanoTime() - start) / (1000);
}

}
```

Person.java

```package com.test.arrayList;

public class Person {
private String name;
private int age;
private double money;

public Person(String name, int age, double money) {
this.name = name;
this.age = age;
this.money = money;
}

getter();
setter();

}
```