Why would iterating over a List be faster than indexing through it?

后端 未结 5 1699
小蘑菇
小蘑菇 2020-12-12 11:38

Reading the Java documentation for the ADT List it says:

The List interface provides four methods for positional (indexed) access to list elements. Li

5条回答
  •  鱼传尺愫
    2020-12-12 12:10

    While the accepted answer is most certainly correct, might I point out a minor flaw. Quoting Tudor :

    Now, going to the other implementation of List which is ArrayList, that one is backed by a simple array. In that case both of the above traversals are equivalent, since an array is contiguous so it allows random jumps to arbitrary positions.

    This is not completely true. The truth is, that

    With an ArrayList, a hand-written counted loop is about 3x faster

    source: Designing for Performance, Google's Android doc

    Note that the handwritten loop refers to the indexed iteration. I suspect its because of the iterator which is used with enhanced for loops. It produces a minor performance in penalty in a structure which is backed by a contiguous array. I also suspect this might be true for the Vector class.

    My rule is, use the enhanced for loop whenever possible, and if you really care about performance, use indexed iteration only for either ArrayLists or Vectors. In most cases, you can even ignore this- the compiler might be optimizing this in the background.

    I merely want to point out that in the context of development in Android, both the traversals of ArrayLists are not necessarily equivalent. Just food for thought.

提交回复
热议问题