zoukankan      html  css  js  c++  java
  • 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循环,这种做法很糟糕,数据量大的时候有可能会导致系统崩溃

  • 相关阅读:
    [Z] Windows 8/10 audio编程
    [Z]The Boost C++ Libraries
    [Z] windows进程在32、64位系统里用户和系统空间的地址范围
    [Z] 关于c++ typename的另一种用法
    [z] 人工智能和图形学、图像处理方面的各种会议的评级
    [Z] 计算机类会议期刊根据引用数排名
    关于windows的service编程
    关于Linux session管理与GUI架构
    搭建框架-ECS.ECommerce
    不调用构造函数而创建一个类型实例
  • 原文地址:https://www.cnblogs.com/mxh-java/p/11069719.html
Copyright © 2011-2022 走看看