Friday, July 30, 2010

Better way of using Lists in loops


Target audience: Beginners

As I always believe, we can think of in anyways to improve the performance of our application. In this post, I explain how we can use loops effectively for list iteration. In most of my projects, I have seen developers code list iteration as follows

for (int j = 0; j < aList.size(); j++) {
....
}

There is nothing wrong in this code can change this piece of code to perform well. If you see carefully, the aList.size() will be invoked every time before the next iteration of loop starts. So, what we can do is, we can assign the size of the list to a variable and use that variable inside the loop. Check the code bellow

int size = aList.size();
for (int j = 0; j < size; j++) {
....
}

This will improve the performance a bit. I can prove this by running the following benchmarking program.

package basics;

import java.util.ArrayList;
import java.util.List;

public class ListSizeExample {
public static void main(String[] args) {

long start = 0;
long end = 0;
List aList = new ArrayList();
for (int i = 0; i < 50; i++) {
aList.add(i);
}

// Using list.size() in the loop
start = System.nanoTime();
for (int i = 0; i < 100; i++) {
for (int j = 0; j < aList.size(); j++) {

}
}
end = System.nanoTime();
System.out.println("Using aList.size(): " + (end - start) / 100);

// Using size, size is assigned with value of list.size()
start = System.nanoTime();
for (int i = 0; i < 100; i++) {
int size = aList.size();
for (int j = 0; j < size; j++) {
}
}
end = System.nanoTime();
System.out.println("Using size: " + (end - start) / 100);
}
}

I have an outer loop for each benchmark code block which runs 100 times and this is just to get the average time taken for the actual loop. If you run the code, you will get an output similar to the following one

Using aList.size(): 3765
Using size: 1256

This proves that the code perform better with a assigned value of length then directly using the list.size() inside the loop

No comments:

Post a Comment