Java循環性能隨筆,java循環隨筆
for iterator做迭代循環性能最好 然後是foreach 然後是提前聲明好變量的for循環 最後是每次都要計算集合size的for
package test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* 性能測試
* @author LinSir
*
*/
public class PerformanceTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Map<String, Object>> list=new ArrayList<Map<String,Object>>();
Map<String, Object> map=new HashMap<String, Object>();
map.put("name", "jams");
map.put("sex", true);
map.put("age", 17);
for (int i = 0; i <100000; i++) {
list.add(map);
}
System.out.println("第一種起始時間:");
long a11=System.currentTimeMillis();
long a1=System.nanoTime();
for (int i = 0; i < list.size(); i++) {
list.get(i).get("name");
list.get(i).get("sex");
list.get(i).get("age");
/*list.get(i).put("a", 999);
list.get(i).remove("sex");*/
}
long a2=System.nanoTime();
long a22=System.currentTimeMillis();
System.out.println("第一種納秒差:"+(a2-a1));
System.out.println("第一種毫秒差:"+(a22-a11));
System.out.println("-----------------------------");
System.out.println("第二種起始時間:");
long b11=System.currentTimeMillis();
long b1=System.nanoTime();
for (Map<String, Object> map2 : list) {
map2.get("name");
map2.get("sex");
map2.get("age");
/*map2.put("a", 999);
map2.remove("sex");*/
}
long b2=System.nanoTime();
long b22=System.currentTimeMillis();
System.out.println("第2種納秒差:"+(b2-b1));
System.out.println("第2種毫秒差:"+(b22-b11));
System.out.println("-----------------------------");
System.out.println("第3種起始時間:");
long c11=System.currentTimeMillis();
long c1=System.nanoTime();
for (Iterator<Map<String, Object>> iterator = list.iterator(); iterator.hasNext();) {
Map<String, Object> map2 = (Map<String, Object>) iterator.next();
map2.get("name");
map2.get("sex");
map2.get("age");
/*map2.put("a", 999);
map2.remove("sex");*/
}
long c2=System.nanoTime();
long c22=System.currentTimeMillis();
System.out.println("第3種納秒差:"+(c2-c1));
System.out.println("第3種毫秒差:"+(c22-c11));
System.out.println("-----------------------------");
System.out.println("第4種起始時間:");
long d11=System.currentTimeMillis();
long d1=System.nanoTime();
int listSize=list.size();
for (int i = 0; i < listSize; i++) {
list.get(i).get("name");
list.get(i).get("sex");
list.get(i).get("age");
/*list.get(i).put("a", 999);
list.get(i).remove("sex");*/
}
long d2=System.nanoTime();
long d22=System.currentTimeMillis();
System.out.println("第4種納秒差:"+(d2-d1));
System.out.println("第4種毫秒差:"+(d22-d11));
System.out.println("-----------------------------");
}
}
//依照以上耗時來判斷for iterator性能大於foreach大於for循環