java中for与for each效率对比
public class ForTest {
public static void main(String[] args){
ArrayList<Integer> array=new ArrayList<Integer>();
for(int i=0;i<1000000;i++){
array.add(i);
}
long t1=new Date().getTime();
long size=array.size();
for(int i=0;i<size;i++){
System.out.println(array.get(i));
}
long t2=new Date().getTime();
long t3=new Date().getTime();
for(Object i : array){
System.out.println(i);
}
long t4=new Date().getTime();
System.out.println("for: "+(t2-t1));
System.out.println("for each: "+(t4-t3));
}
}
for: 12079
for each: 11750
for each 结构效率要高于for结构,这是因为for each执行循环的同时还执行了付值
若都只单做循环处理时:
for:
long size=array.size();
for(int i=0;i<size;i++){
}
for each:
for(Object i : array){
}
for: 32
for each: 390
for的效率明显高于for each