forサイクルを不適切に使用すると、速度が千倍遅くなります

2884 ワード

テストにより、forループ構文を不適切に使用すると、クエリの効率が千倍遅くなることが分かった.謹んで記す
 
	/**
	 * TODO  . for ,list 46000 . 1000 .
	 * 
	 * 2016 4 6 
	 * novelbio fans.fan
	 */
	public void testArray() {
		String filePathAndName = "GO-Analysis_BP_peak0_All.xlsx";

		List> lsExcel = ExcelOperate.readLsExcel2007SheetFast(filePathAndName, 2);
		Object[] array = lsExcel.toArray();
		
		long time2 = System.currentTimeMillis();
		// for 
		List lsContent = null;
		for (int i = 0; i < lsExcel.size(); i++) {
			lsContent = lsExcel.get(i);
			int len = lsContent.size();
		}
		long time3 = System.currentTimeMillis();
		System.out.println("process data=" + (time3 - time2));
		
		long time4 = System.currentTimeMillis();
		// for 
		for (List lsData : lsExcel) {
			int len = lsData.size();
		}
		long time5 = System.currentTimeMillis();
		System.out.println("process2 data=" + (time5 - time4));
	}
	
	public void testArray2() {
		String filePathAndName = "GO-Analysis_BP_peak0_All.xlsx";

		List> lsExcel = ExcelOperate.readLsExcel2007SheetFast(filePathAndName, 2);
		Object[] array = lsExcel.toArray();
		
		long time2 = System.currentTimeMillis();
		// for 
		List lsContent = null;
		for (int i = 0; i < array.length; i++) {
			lsContent = (List) array[i];
			int len = lsContent.size();
		}
		long time3 = System.currentTimeMillis();
		System.out.println("testArray2 process data=" + (time3 - time2));
		
		long time4 = System.currentTimeMillis();
		// for 
		lsContent = null;
		for (Object lsData : array) {
			lsContent = (List) lsData;
			int len = lsContent.size();
		}
		long time5 = System.currentTimeMillis();
		System.out.println("testArray2 process2 data=" + (time5 - time4));
	}
	
	public void testArray3() {

		List lsExcel = new ArrayList<>(50000);
		for(int i = 0; i < 50000; i++){
			lsExcel.add((int)(Math.random() * 10000));
		}
		
		long time2 = System.currentTimeMillis();
		// for 
		for (int i = 1; i < lsExcel.size(); i++) {
			int a = lsExcel.get(i);
			int len = a;
		}
		long time3 = System.currentTimeMillis();
		System.out.println("testArray3 process data=" + (time3 - time2));
		
		long time4 = System.currentTimeMillis();
		lsExcel.remove(0);
		// for .
		for (Integer a : lsExcel) {
			int len = a;
		}
		long time5 = System.currentTimeMillis();
		System.out.println("testArray3 process2 data=" + (time5 - time4));
	}

実行結果
process data=7804
process2 data=5
testArray2 process data=4
testArray2 process2 data=3
testArray3 process data=3
testArray3 process2 data=1

のようにhttp://www.jianshu.com/p/2fecd8d66829配列で実現するには、この例のテストから見ると、通常のforサイクルを用いることが推奨される.実際の差も大きくない.
ただしlistネストタイプであれば.普通のforサイクルで千倍も遅くなります.