0

Given a List<T>, which is the preferred way to iterate on Android? Are there any performance differences on a modern day Android device?

for (int i=0; i<list.size(); i++) {
    T element = list.get(i);
    ...
}

or

for (T element : list) {
    ...
}

Edit: This question is specific to the Android runtime. The other "duplicate" question doesn't address the Android specifics.

Steve Kuo
  • 61,876
  • 75
  • 195
  • 257
  • the first version is slightly slower – Blackbelt May 13 '15 at 20:31
  • @Blackbelt There is no way the first version is slower when written correctly (size should be saved in a variable so its not called N times). The second requires a function call to iterate so it will always be slower. Its just a matter of it the cost is enough anyone should care (probably not). – Gabe Sechan May 13 '15 at 21:03
  • First first one is slower if the List is a LinkedList – Steve Kuo Oct 27 '15 at 14:04
  • This question is Android specific, I disagree that it's a duplicate. – Steve Kuo Oct 27 '15 at 14:05

1 Answers1

0

The second version -- the for-each loop -- allocates an Iterator object, which can be undesirable for Android code. The first version may be preferable, as long as you're sure the List is a RandomAccess implementation such as ArrayList.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413