Home - Search - Site Map - Site Graph | Contact
( Last Modified: 2008 November 03rd 03:04 PM )

Java performance explanations and optimizations

(Publishing in Progress)

Repeated array index, member variable or method calls in loops are slow

Fix: save to scalars.

In other words any loop invariant should be pre-calculated and saved before the loop.

For example:

for ( ... ) {

i = this.member; // BAD
j = array[2]; // BAD
k = object.getValue(); //BAD

}

Instead assign the values to local varaible before the loop

int member = this.member;
int element = array[2];
int value = object.getValue();


for ( ... ) {

i = member; // GOOD
j = element; // GOOD
k = value; //GOOD

}

Mulitple member varible references in methods

Fix: save to scalars.

For example consider the method:

public void method( ... ) {

System.out.println( this.member );
...
int new Value = X / this.member;
...
... + this.member

}

If you assign the member value to a scalar at the beginning of a method you save dereferencing each time.

public void method( ... ) {

int scalar = this.member
System.out.println( scalar );
...
int new Value = X / scalar;
...
... + scalar;

}

Repeated Object creation causes garbage collection

invokeStatic faster than invokeVirtual

Is this still true on all embedded VMs?

invokeInterface must be looked up each time (not just first time like invokeVirtual)

switch statements have two possible byte codes

"tableswitch" vs "lookupswitch"

multidimensional arrays (requires multiple index checks, save frequently used data in scalars etc...)

Slow constructs (casting etc...)

Socket.setSoTimeout() is slow

Constant folding (use final when ever possible)

For example in the code below, if you were to look up the bytecode you would notice that the constants are not folded for string s4.

The means the strings must be concatenated each time (creating stringbuffers etc....)

public void constantFolding() {
final String s1 = "TEST" + "CONSTANT" + "FOLDING"; // Constants Folded
String s2 = "TEST" + "CONSTANT" + "FOLDING"; // Constants Folded

String s3 = "TEST" + "CONSTANT" + "FOLDING" + s1; // Constants Folded
String s4 = "TEST" + "CONSTANT" + "FOLDING" + s2; // Constants NOT Folded
}

Memory and Resources:

Each object has overhead for syncrhonization even if it is not used

Each thread has a default stack size that takes up memory

Multidemensional arrays create many objects.

For example if you have an array Object[][] array[n][m]

The n dimension array is one Object that contains n Objects that are arrays of length m. For a total of n + 1 objects.

If possible create parallel single dimension arrays to save on object creation and garbage collection

 

( Page Created: 2008 October 20th 02:45 PM )