(number);
for (int i = 0; i < number; i++) {
list.add(Integer.toString(i));
}
System.out.println("测试列表的性能...");
// 我们用foreach方式测试
long begin = System.nanoTime();
for (String i : list) {
testMethod(i);
}
System.out.printf("%10s=%10d\n", "foreach", System.nanoTime() - begin);
begin = System.nanoTime();
// 下面我们用Iterator测试
Iteratorit = list.iterator();
while (it.hasNext()) {
testMethod(it.next());
}
System.out.printf("%10s=%10d\n", "iterator", (System.nanoTime() - begin));
// 第三种,我们用index进行
begin = System.nanoTime();
for (int i = 0; i < number; i++) {
testMethod(list.get(i));
}
System.out.printf("%10s=%10d\n", "for", (System.nanoTime() - begin));
System.out.println("测试数组的性能...");
// 我们再来测试数组
String[] strArr = new String[number];
for (int i = 0; i < number; i++) {
strArr[i] = Integer.toString(i);
}
// 我们用foreach方式测试
begin = System.nanoTime();
for (String i : strArr) {
testMethod(i);
}
System.out.printf("%10s=%10d\n", "foreach", System.nanoTime() - begin);
// 第二种,我们用index进行
begin = System.nanoTime();
for (int i = 0; i < number; i++) {
testMethod(strArr[i]);
}
System.out.printf("%10s=%10d\n", "for", System.nanoTime() - begin);
}
public static void testMethod(String str) {
}
}
2 运行结果
测试列表的性能...
foreach= 41997864
iterator= 43951774
for= 14351289
测试数组的性能...
foreach= 1751863
for= 1484585
3 结论:
foreach的性能很一般,for才是的,推荐大家使用。