Efficient loop through Java List

前端 未结 6 950
花落未央
花落未央 2021-02-07 09:51

The following list is from the google I/O talk in 2008 called \"Dalvik Virtual Machine Internals\" its a list of ways to loop over a set of objects in order from most to least e

6条回答
  •  北恋
    北恋 (楼主)
    2021-02-07 10:09

    I guess that the compiler optimizes (3) to this (this is the part where I'm guessing):

    for (int i =0; i < array.length; ++i)
    {
        Type obj = array[i];
    
    }
    

    And (7) can't be optimized, since the compiler doesn't know what kind of Iterable it is. Which means that it really has to create a new Iterator on the heap. Allocating memory is expensive. And every time you ask for the next object, it goes trough some calls.

    To give a rough sketch of what is happens when (7) gets compiled (sure about this):

    Iterable iterable = get_iterable();
    Iterator it = iterable.iterator(); // new object on the heap
    while (it.hasNext()) // method call, some pushing and popping to the stack
    {
        Type obj = it.next(); // method call, again pushing and popping
    
    
    }
    

提交回复
热议问题