Performance: Iterating through a List in Java

前端 未结 9 2158
半阙折子戏
半阙折子戏 2020-12-29 20:33

Is it slower to iterate through a list in Java like this:

for (int i=0;i

as opposed to:

9条回答
  •  梦毁少年i
    2020-12-29 20:57

    THERE CAN BE A DIFFERENCE.

    If a List implementation also implements java.util.RandomAccess (like ArrayList does), then it is just about faster to use its get() method over an interator.

    If it does not implement java.util.RandomAccess (for example, LinkedList does not), then it is substantially faster to use an iterator.

    However, this only matter if you are using lists containing thousands of (possibly scattered) objects or that are constantly traversed (as if performing copious amounts of math on List objects representing numerical vectors.)

提交回复
热议问题