foreach與正常for循環效率對比


/**
 * 測試for與froEach效率
 * @author 15735400536
 *
 */
public class TestList {
	public static void main(String[] args) {
		List<Integer> array = new ArrayList<Integer>();
		List<Integer> link = new LinkedList<Integer>();
		
		long startTime = 0;
		long endTime = 0;
		
		startTime=System.currentTimeMillis();
		for(int i=0; i<100000; i++) {
			array.add(i);
		}
		endTime=System.currentTimeMillis();
		System.out.println("ArrayList add 花費時間: " + (endTime - startTime));
		
		startTime=System.currentTimeMillis();
		for(int i=0; i<100000; i++) {
			link.add(i);
		}
		endTime=System.currentTimeMillis();
		System.out.println("LinkedList add 花費時間: " + (endTime - startTime));
		
		startTime=System.currentTimeMillis();
		for(int i=0; i<100000; i++) {
			array.get(i);
		}
		endTime=System.currentTimeMillis();
		System.out.println("for 遍歷  ArrayList get 花費時間: " + (endTime - startTime));
		
		startTime=System.currentTimeMillis();
		for(int i=0; i<100000; i++) {
			link.get(i);
		}
		endTime=System.currentTimeMillis();
		System.out.println("for 遍歷 LinkedList get 花費時間: " + (endTime - startTime));
		
		startTime=System.currentTimeMillis();
		for(int i : array) {
			//System.out.println(i);
		}
		endTime=System.currentTimeMillis();
		System.out.println("forEach 遍歷  ArrayList get 花費時間: " + (endTime - startTime));
		
		startTime=System.currentTimeMillis();
		for(int i : link) {
			//System.out.println(i);
		}
		endTime=System.currentTimeMillis();
		System.out.println("forEach 遍歷 LinkedList get 花費時間: " + (endTime - startTime));
	}
}

用for循環arrayList 10萬次花費時間:2毫秒。 用foreach循環arrayList 10萬次花費時間:3毫秒。 用for循環linkList 10萬次花費時間:6163毫秒。 用foreach循環linkList 10萬次花費時間:4毫秒。

循環ArrayList時,普通for循環比foreach循環花費的時間要少一點。 循環LinkList時,普通for循環比foreach循環花費的時間要多很多。

當我將循環次數提升到一百萬次的時候,循環ArrayList,普通for循環還是比foreach要快一點;但是普通for循環在循環LinkList時,程序直接卡死。

ArrayList:ArrayList是采用數組的形式保存對象的,這種方式將對象放在連續的內存塊中,所以插入和刪除時比較麻煩,查詢比較方便。

LinkList:LinkList是將對象放在獨立的空間中,而且每個空間中還保存下一個空間的索引,也就是數據結構中的鏈表結構,插入和刪除比較方便,但是查找很麻煩,要從第一個開始遍歷。

結論:

需要循環數組結構的數據時,建議使用普通for循環,因為for循環采用下標訪問,對於數組結構的數據來說,采用下標訪問比較好

需要循環鏈表結構的數據時,一定不要使用普通for循環,這種做法很糟糕,數據量大的時候有可能會導致系統崩潰


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM