Class member variable initialization

While declaring the class member variables we have to be very confident about the behavior of the member variables. For example some variable are constant and will be same across the class life cycle and some are instance variables which will be tightly bind with the object (instance) of the class.

When an instance of a class is created using new, initialization of the class’s instance variables create for each unique instance.

Always use the static for the member variable which doesn’t change across the objects of the class.

I would try to check the performance using the below code sample:

public class TestClassVariable {

public TestClassVariable() {

// do nothing

}

public String country[] = { “India”, “USA”, “China”, “UK” };

public static void main(String s[]) {

long start, end;

int[] a = new int[1000000];

start = System.currentTimeMillis();

for (int j = 0; j length; j++) {

TestClassVariable tstClassVar = new TestClassVariable();

}

end = System.currentTimeMillis();

System.out.println(end – start + ” “

+ ” milli seconds execution time”);

}

}

Result: 94 milli seconds execution time

In the above code we used country as class instance variable and it takes 94MS but as we know country could be make as static member variable because it will be not going to change across the instances so the correct way to use as static member variable.

So we can change the program slightly and see the figures again


public class TestClassVariable {

public TestClassVariable() {

// do nothing

}

public static String country[] = { “India”, “USA”, “China”, “UK” };

public static void main(String s[]) {

long start, end;

int[] a = new int[1000000];

start = System.currentTimeMillis();

for (int j = 0; j length; j++) {

TestClassVariable tstClassVar = new TestClassVariable();

}

end = System.currentTimeMillis();

System.out.println(end – start + ” “

+ “milli seconds execution time”);

}

}

Result: 16 milli seconds execution time

We could easily figure it out the performance get enhance 6 times then the original one



Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s