Monday 15 February 2016

Optimizing Java Code !! Performance Matters !!

General optimization techniques
Optimiziation is one of most serious concern of Java. Writing a program and generating output is altogether different than to increase the performance of application. There are different ways to making the optimization, in this blog we will be discussing few :-) 

Strength reduction
Strength reduction occurs when an operation is replaced by an equivalent operation that executes faster. The most common example of strength reduction is using the shift operator to multiply and divide integers by a power of 2. For example, x >> 2 can be used in place of x / 4, and x << 1 replaces x * 2.
Common sub expression elimination
Common sub expression elimination removes redundant calculations. Instead of writing
double x = d * (lim / max) * sx;
double y = d * (lim / max) * sy;
the common sub expression is calculated once and used for both calculations:
double depth = d * (lim / max);
double x = depth * sx;
double y = depth * sy;
Code motion
Code motion moves code that performs an operation or calculates an expression whose result doesn't change, or is invariant. The code is moved so that it only executes when the result may change, rather than executing each time the result is required. This is most common with loops, but it can also involve code repeated on each invocation of a method. The following is an example of invariant code motion in a loop:

for (int i = 0; i < x.length; i++)
 x[i] *= Math.PI * Math.cos(y);
becomes
double picosy = Math.PI * Math.cos(y);for (int i = 0; i < x.length; i++)
x[i] *= picosy;
Unrolling loops
Unrolling loops reduces the overhead of loop control code by performing more than one operation each time through the loop, and consequently executing fewer iterations. Working from the previous example, if we know that the length of x[] is always a multiple of two, we might rewrite the loop as:
double picosy = Math.PI * Math.cos(y);for (int i = 0; i < x.length; i += 2) {
x[i] *= picosy;
x[i+1] *= picosy;
}
In practice, unrolling loops such as this -- in which the value of the loop index is used within the loop and must be separately incremented -- does not yield an appreciable speed increase in interpreted Java because the bytecodes lack instructions to efficiently combine the "+1" into the array index.
All of the optimization tips in this article embody one or more of the general techniques listed above.

No comments:

Post a Comment

Attend Online Java Certification Training and excel your career

Hello Java Developer,  Are you staying at home and worried about your future? Do not waste the time in worrying. International certifi...