package my.code;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class TestFor {
public TestFor() {
Integer[] tarray = new Integer[15000000];
for (int i = 0; i < tarray.length; i++) {
tarray[i] = 0;
}
List<Integer> tlist = Arrays.asList(tarray);
// 初始化完毕,开始测试
long start = 0, end = 0;
// 先测试数组性能
// 一般模式
start = System.currentTimeMillis();
for (int i = 0; i < tarray.length; i++) {
}
end = System.currentTimeMillis();
System.out.println("数组_一般模式:" + (end - start));
// 预赋值array模式
start = System.currentTimeMillis();
for (int i = 0, n = tarray.length; i < n; i++) {
}
end = System.currentTimeMillis();
System.out.println("数组_预赋值模式:" + (end - start));
// ForEach模式(array)
start = System.currentTimeMillis();
for (Integer i : tarray) {
}
end = System.currentTimeMillis();
System.out.println("数组_ForEach模式:" + (end - start));
// 测试List性能
// 一般模式
start = System.currentTimeMillis();
for (int i = 0; i < tlist.size(); i++) {
}
end = System.currentTimeMillis();
System.out.println("List_一般模式:" + (end - start));
// 预赋值List模式
start = System.currentTimeMillis();
for (int i = 0, n = tlist.size(); i < n; i++) {
}
end = System.currentTimeMillis();
System.out.println("List_预赋值模式:" + (end - start));
// ForEach模式(list)
start = System.currentTimeMillis();
for (Integer integer : tlist) {
}
end = System.currentTimeMillis();
System.out.println("List_ForEach模式:" + (end - start));
// Iterator
start = System.currentTimeMillis();
Iterator itr = tlist.iterator();
while (itr.hasNext()) {
itr.next();
}
end = System.currentTimeMillis();
System.out.println("List_Iterator模式:" + (end - start));
}
/**
* @param args
*/
public static void main(String[] args) {
new TestFor();
}
}
输出结果:如下,看出来了吧for最好
数组_一般模式:2
数组_预赋值模式:3
数组_ForEach模式:3
List_一般模式:2
List_预赋值模式:2
List_ForEach模式:24
List_Iterator模式:8
对foreach、for、iterator测试
最新推荐文章于 2024-04-19 21:46:37 发布