Make your Java Application run faster - Part 1 - Compiler Optimizations

It is a general concern that java applications run slower that C and C++ applications. Which this concern is partly true; there are some things that you can do to make your applications faster.

In this series of I will be presenting several articles on optimizing your java applications and suggest several techniques to make them run faster.

In this Part we shall see the various Compiler Level Optimizations.

Before going on to the changing your code, it is better to know the optimization that the compiler is already doing. Java compiler is intelligent and does many optimizations that even if you write sloppy code the compiler generates decent, optimized byte code. The following are some of the optimizations that the java compiler does.

Code Movement: moves simple expressions outside a loop if the variables used in that expression do not change inside the loop.

For Example:

int x = 15;
int y = 10;
int arr[10];
for (i=0; i<10;i++)

arr[i] = x + y;

Because x and y are invariant and do not change inside of the loop, their addition doesn't need to be performed for each loop iteration. So the compiler moves the addition of x and y outside the loop, thus creating a more efficient loop. For example, the optimized code could look like the following:

int x = 15;
int y = 10;
int z = x + y;
int arr[10];
for (i=0; i<10;i++)

arr[i] = z;

Constant folding: Constant folding refers to the compiler precalculating constant expressions. For example, examine the following code:

static final int length = 25;
static final int width = 10;
int res = length * width;

During execution these values will not be multiplied; instead, multiplication is done at compile time. The code for the following variable assignment is modified to produce bytecode that represents the product of width and length:

int res = 250;

Limited dead code elimination: No code is produced for statements like

if(false)

{
...
}

Dead code elimination does not affect the code's runtime execution. It does, however, reduce the size of the generated class file.

Other Compiler Related Options

There are also just in just-in-time (JIT) compilers that convert Java bytecodes into native code at run time. Several are available, and while they can increase the execution speed of your program dramatically, the level of optimization they can perform is constrained because optimization occurs at run time. A JIT compiler is more concerned with generating the code quickly than with generating the quickest code.

You can also use native code compilers that compile Java directly to native code should offer the greatest performance but at the cost of platform independence.