不恰当的使用for循环,会使速度慢千倍

测试发现,不恰当的使用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循环会慢上千倍.

你可能感兴趣的:(java基础)