Monday, December 14, 2009

Java For-Loop Effeciency: .size()

Many majors in most colleges require Comp Sci to some degree, generally teaching java. I have always found the underlying pinnings of languages very interesting, so this may bore some of my readers, and some, it may catch your interest.

This makes perfect sense, but I do not think many people realize it. It is better to allocate a variable outside a for loop as apposed to using a .size method inside it. Of course, being ever curious, I decided to test this. Bellow is the code I made (yes, its bad, but it was written quickly.)


import java.util.ArrayList;


public class Tester {


public static void main(String []argv) {

ArrayList test = new ArrayList();

test.add("a");

test.add("b");

test.add("a");

test.add("b");

test.add("a");

test.add("b");

test.add("a");

test.add("b");

test.add("a");

test.add("b");

test.add("a");

test.add("b");

test.add("a");

test.add("b");

test.add("a");

test.add("b");

test.add("a");

test.add("b");

test.add("a");

test.add("b");

test.add("a");

test.add("b");

test.add("a");

test.add("b");

test.add("a");

test.add("b");

test.add("a");

test.add("b");

test.add("a");

test.add("b");

System.out.println("The array has " + test.size() + " objects");

long startTime = System.nanoTime();

withSize((ArrayList)test.clone());

long timeDiff = System.nanoTime() - startTime;

System.out.println("With bad coding style :" + timeDiff + "");

long startTime2 = System.nanoTime();

withoutSize((ArrayList)test.clone());

long timeDiff2 = System.nanoTime() - startTime2;

System.out.println("With good coding style :" + timeDiff2 + "");

}

public static void withSize( ArrayList ar) {

for(int a = 0; a<ar.size()-1; a++) {

ar.set(a,ar.get(a)+ar.get(a+1));

}

}

public static void withoutSize( ArrayList ar) {

//Notice that ar.size() is not in the loop

int b = ar.size();

for(int a = 0;a<ar.size()-1;a++) {

ar.set(a,ar.get(a)+ar.get(a+1));

}

}

}

You will find pretty consistently that the second loop executes quicker. As for memory allocation assigning int b outside a loop, an int is a 32 bit object, which is really not much considering how big we make our memory and that it will be dealloc'd after the method completes. Of course, the time difference is in nanoseconds, but over time I am sure the for loops in code do build up, especially as code gets longer and longer.

An important, almost ironic note, this will not work on Windows, the timer does not have a good enough resolution.

2 comments:

  1. For the record and as a note for future readers, this example and test is flawed. By using test.clone(), I am allocating additional memory and that alone can cause additional overhead in the test cases with unpredictable consequences.

    ReplyDelete