Advertisement

Sri Lanka's First and Only Platform for Luxury Houses and Apartment for Sale, Rent

Wednesday, August 17, 2011

Performance Testing

On my spare time I have been doing some Performance Testing mechanisms in Java.
I just wrote a small code snippet and ran it in a Worker thread and tried to improve
the performance of it. Even though this is small the lesson I learned was immense.

This is the worker class I used.

import java.util.concurrent.*;


public class Callee implements Callable<Integer> {
public Integer call() {
int i = 0;
while(i < 10000) {
System.out.println(i);
i++;
}
return i;
}
}


And the worker was called by the following class

import java.util.concurrent.*;

import java.awt.*;

public class Caller {
public static void main(String[] args)throws Exception {
long startFreeMemory = Runtime.getRuntime().freeMemory();
long startTime = System.currentTimeMillis();
ExecutorService exec = Executors.newCachedThreadPool();
Future<Integer> f = exec.submit(new Callee());
exec.shutdown();
System.out.println("Future is "+f.get());
long endTime = System.currentTimeMillis();
long endFreeMemory = Runtime.getRuntime().freeMemory();
System.out.println("Memory used : "+(startFreeMemory - endFreeMemory));
System.out.println("Duration : "+(endTime - startTime));
}
}


Testing was done in Intel Core 2 Duo Process with 2.93 GHz and 2 Gb of RAM.

The initial program ran for 672 Milliseconds and Used 674408 units of RAM.

Then the Callee class was changed to the following.

import java.util.concurrent.*;


public class Callee implements Callable<Integer> {
public Integer call() {
int i = 0;
StringBuilder sb = new StringBuilder();
while(i < 10000) {
sb.append(i+"\n");
i++;
}
System.out.print(sb.toString());
return i;
}
}


Using a StringBuffer without directly printing to the screen reduced the execution time by 188 Milliseconds but the RAM units used increased to 828288.

But just changing

sb.append(i+"\n");



to

sb.append(i).append("\n");



reduced the RAM Usage by almost half from the previous implementation.

1 comment:

Jeremy Keiper said...

Wow ... didn't realize string builders made that much of a difference, thanks!