Home Classroom Android Development Agile development of Android apps – Speed Tip #1: Looping over an...

Agile development of Android apps – Speed Tip #1: Looping over an ArrayList

Efficient programming on mobile devices not only saves CPU, but battery as well

Everyone uses ArrayLists these days because they’re flexible. When you iterate over it, it allows you to use the enhanced for loop:

for (MyClass object : myArrayList) {
  ...
}

You use this because it’s simple to understand and easy to use. Did you know it’s consistently 3 times slower than the way you learned to do it in high-school? :)

for (int i=0; i<myArrayList.size(); i++){
  final MyClass object = myArrayList.get(i);
  ...
}

And you can squeeze even more out of this by looping it the other way around. If you check the condition you will access the ArrayList’s size() function every time you increment the counter. But if you loop the other way around you will only read in the beginning and then countdown towards 0, a constant:

for (int i=myArrayList.size()-1; i>-1; i--){
  final MyClass object = myArrayList.get(i);
  ...
}

Don’t forget to write i–. The first time you’ll try this you’ll write i++ out of habit and you won’t know why it crashed .This subject is pretty deep and it involves the JIT (Just In Time compiler) and automatic usage of Iterators behind the scenes as well. When you’re not sure what really matters in terms of speed the best way to figure it out is to write a small test yourself and run it directly on the emulator by measuring time the good old way with System.currentMillis()!

Comments

comments

Teo is a software engineer from Romania, he works at Atoss developing a workforce management product. He is a former Google API Guru and Google Desktop 'Hall of Fame' developer.

NO COMMENTS

Leave a Reply