欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-04-26 22:01:49
...

测试发现,不恰当的使用for循环语法,会使查询效率慢千倍.谨记.

 

	/**
	 * TODO 测试发现.两种不同的for写法,list中46000条数据.效率差了1000多倍.
	 * 
	 * 2016年4月6日
	 * novelbio fans.fan
	 */
	public void testArray() {
		String filePathAndName = "GO-Analysis_BP_peak0_All.xlsx";

		List<List<String>> lsExcel = ExcelOperate.readLsExcel2007SheetFast(filePathAndName, 2);
		Object[] array = lsExcel.toArray();
		
		long time2 = System.currentTimeMillis();
		//第一种for写法
		List<String> 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<String> 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<List<String>> lsExcel = ExcelOperate.readLsExcel2007SheetFast(filePathAndName, 2);
		Object[] array = lsExcel.toArray();
		
		long time2 = System.currentTimeMillis();
		//第一种for写法
		List<String> lsContent = null;
		for (int i = 0; i < array.length; i++) {
			lsContent = (List<String>) 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<String>) lsData;
			int len = lsContent.size();
		}
		long time5 = System.currentTimeMillis();
		System.out.println("testArray2 process2 data=" + (time5 - time4));
	}
	
	public void testArray3() {

		List<Integer> 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循环会慢上千倍.