Wednesday, July 28, 2010

Improve the Application’s performance by using primitive constants

Target audience: Beginners

We use hundreds of constants in our application. It’ll be even thousands in a large scale projects. These constants are used again and again at runtime. Improving the performance of an application in any ways is advisable.So, it will be great if we can think about improving the performance while using constants.
I would suggest using primitive constants where ever it is possible than using String constants. It is advisable not only for better memory usage but also for better performance. The following benchmark program shows the difference. The most possible usage of constants is comparison. So i use comparison for benchmarking.

package basics;

public class ConstantsExample {

public static final int RED = 1;
public static final int GREEN = 2;

public static final String SRED = "RED";
public static final String SGREEN = "GREEN";

// Main methods
public static void main(String[] args) {
long start = 0;
long end = 0;
int red = 1;
String sred = "RED";

// Benchmark primitive constants
start = System.nanoTime();
for (int i = 0; i < 100; i++) {
if (RED == red) {
end = System.nanoTime();
System.out.println("Primitive comparision: "+ (end - start));

// Benchmark String constants
start = System.nanoTime();
for (int i = 0; i < 100; i++) {
if (SRED.equals(sred)) {
end = System.nanoTime();
System.out.println("String comparision: "+(end - start));

If you run this program then you will get the results similar to bellow one

Primitive comparision: 4610
String comparision: 21721

Looks good ha!

No comments:

Post a Comment