why is the enhanced for loop more efficient than the normal for loop

后端 未结 7 1757
一整个雨季
一整个雨季 2020-12-01 00:35

I read that the enhanced for loop is more efficient than the normal for loop here:

http://developer.android.com/guide/practices/performance.html#fo

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 01:02

    I am myself surprised in a little experiment i did today with above mentioned points. So what i did was that i inserted a certain number of elements to a linked list and iterated through it using the above mentioned three methods 1)using advanced for loop 2) using Iterator 3) using simple loop and get()
    I guess programmers such as you guys can better understand what i did by seeing the code.

    long advanced_timeElapsed,iterating_timeElapsed,simple_timeElapsed;
        long first=System.nanoTime();
        for(Integer i: myList){
            Integer b=i;
        }
        long end= System.nanoTime();
        advanced_timeElapsed=end-first;
        System.out.println("Time for Advanced for loop:"+advanced_timeElapsed);
        first=System.nanoTime();
        Iterator it = myList.iterator();
        while(it.hasNext())
        {
            Integer b=it.next();
        }
        end= System.nanoTime();
        iterating_timeElapsed=end-first;
        System.out.println("Time for Iterating Loop:"+iterating_timeElapsed);
        first=System.nanoTime();
        int counter=0;
        int size= myList.size();
        while(counter

    The results where not what i expected . Following is the graph of time elapsed in 3 cases. Time Elapsed Graph

    Y axis-time elapsed X axis-test case
    test case1:10 inputs
    test case2:30 inputs
    test case3:50 inputs
    test case4:100 inputs
    test case5:150 inputs
    test case6:300 inputs
    test case7:500 inputs
    test case8:1000 inputs
    test case9:2000 inputs
    test case10:5000 inputs
    test case11:10000 inputs
    test case12:100000 inputs

    Here you can see that simple loop performs way better than others.if you find any errors in the code above , do reply and i will check again. will update on this further after i dig through bytecode and see what is happening under the hood. My apologies for such a long response but i like to be descriptive. Philip

提交回复
热议问题