Performance: Iterating through a List in Java

前端 未结 9 2149
半阙折子戏
半阙折子戏 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:03

    No. It is faster (or should be faster) when the list also implements: RandomAccess (as ArrayList does and LinkedList doesn't).

    However, you should always use the latter :

     for( Object o: list ) {
     }
    

    and only switch to the former if your have substantial evidence that you're having a performance issue using it (for instance, you profile your application and as result you see as a point for improvement this section of code).

    By not doing so, you risk not being able to switch your implementation in a later refactoring if your application requires it (because you would be tied to the for( int i = 0 ; i < list.size(); i++ ) idiom).

提交回复
热议问题