Performance: Iterating through a List in Java

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

    Created a microbenchmark for the question and was surprised to see for-each runing 2x-3x faster than an indexed loop. The only explanation I have is that for-each version might not require range checks which are made by ArrayList.get(int index).

    For very small lists (10 elements) the result was about the same. For 100 elements for-each is 1.5x faster, for 10000-100000 elements it is faster 2x-3x times.

    The tests are run on a random dataset and checksums are being verified at the end, so JIT chearing is very unlikely to take place in these.

提交回复
热议问题