Performance: Iterating through a List in Java

前端 未结 9 2146
半阙折子戏
半阙折子戏 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条回答
  •  攒了一身酷
    2020-12-29 21:07

    I didn't look myself into the code of get() of all List implementations so maybe what I will write is some FUD. What I have learned is that using the get(i) in for loop will result in an iteration over the whole list over and over again each loop run. Using an Iterator (like enhanced for loop does) will just move the iterator the the next list element without iterating the whole list again.

    My conclusion is that using iterators or the enhanced for loop should be more performant since using get() will result in complexity O(n^2) instead of O(n).

提交回复
热议问题