zoukankan      html  css  js  c++  java
  • java list三种遍历方法性能比較

        从c/c++语言转向java开发,学习java语言list遍历的三种方法,顺便測试各种遍历方法的性能,測试方法为在ArrayList中插入1千万条记录,然后遍历ArrayList,发现了一个奇怪的现象,測试代码例如以下:

    package com.hisense.tiger.list;
    
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    
    public class ListTest {
    	public static void main(String[] args)
    	{
    		List<String> list = new ArrayList<String>();
    		long t1,t2;
    		for(int j = 0; j < 10000000; j++)
    		{
    			list.add("aaaaaa" + j);
    		}
    		System.out.println("List first visit method:");
    		t1=System.currentTimeMillis();
    		for(String tmp:list)
    		{
    			//System.out.println(tmp);
    		}
    		t2=System.currentTimeMillis();
    		System.out.println("Run Time:" + (t2 -t1) + "(ms)");
    		System.out.println("List second visit method:");
    		
    		t1=System.currentTimeMillis();
    		for(int i = 0; i < list.size(); i++)
    		{
    			list.get(i);
    			//System.out.println(list.get(i));
    		}
    		t2=System.currentTimeMillis();
    		System.out.println("Run Time:" + (t2 -t1) + "(ms)");
    		
    		System.out.println("List Third visit method:");
    		Iterator<String> iter = list.iterator();
    		
    		t1=System.currentTimeMillis();
    		while(iter.hasNext())
    		{
    			iter.next();
    			//System.out.println(iter.next());
    		}
    		t2=System.currentTimeMillis();
    		System.out.println("Run Time:" + (t2 -t1) + "(ms)");
    				
    		System.out.println("Finished!!!!!!!!");
    		
    		
    	}
    }


        測试结果例如以下:

    List first visit method:
    Run Time:170(ms)
    List second visit method:
    Run Time:10(ms)
    List Third visit method:
    Run Time:34(ms)
    Finished!!!!!!!!

        測试的结论非常奇怪,第一种方法是java语言支持的新语法,代码最简洁,可是在三种方法中,性能确是最差的,取size进行遍历性能是最高的,求牛人解释?

        


         

  • 相关阅读:
    Spring BeanFactory与FactoryBean的区别及其各自的详细介绍于用法
    解决 vim 报错:the imp module is deprecated in favour of importlib
    SIFT了解,哪些方法可以在现在的AI算法中借鉴?
    CLAHE
    实际算法项目工程上手日志C/C++
    OS X 切换gcc版本
    opencv3.4.2 cmake错误:in-source builds are not allowed
    C++ opencv 计算两张图像的PSNR相似度
    如何在OS X 中使用markdown + latex混合记笔记?
    给anaconda 换源
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/4307096.html
Copyright © 2011-2022 走看看