Performance Tuning : Java

Performance Tuning : Java

Performance Tuning Oracle

  • optimizations that can make your code run faster or use less memory

  • The important rule of thumb is this: only optimize where it’s needed. Said another way: if it ain’t broke, don’t fix it. I suggest that your first pass at coding your application should concentrate on cleanliness and maintainability. If there are performance problems, identify them and begin optimizing. You shouldn’t be optimizing code as you write it—that’s just likely to result in hard-to-read, hardto-maintain code. Write first, then test, then optimize

  • do not optimize while you are writing a code: first write it and test it if it is working and then optimize it.

find the memory taken by code

Runtime runtime = Runtime.getRuntime(); 
long before, after; 
System.gc(); 
before = runtime.freeMemory();
Object newObject = new String(); 
after = runtime.freeMemory(); 
long size = before - after;

find the time taken by code

long start, finish; 
start = System.currentTimeMillis();
someMethod(); finish = System.currentTimeMillis();
long duration = finish - start;

Creating and discarding object

Creating an object inside loop
// Set up the inputs and results arrays. 
Object[] inputs = new Object[0];
int[] results = new int[0];
// Process each input to calculate a result.
int length = inputs.length;
for (int i = 0; i < length; i++)
{ Processor p = new Processor(inputs[i]);
 results[i] = p.calculateResult();
  }
  • creating object inside for loop is an issue : we have to pay price when the object is created and then later when the object is garbage collected

  • **Why there is a cost when the object is garbage collected **

  • Optimized Code

// Set up the inputs and results arrays. 
Object[] inputs = new Object[0]; 
int[] results = new int[0];
// Process each input to calculate a result.
int length = inputs.length; 
Processor p = new Processor(); 
for (int i = 0; i < length; i++)
{ 
p.setInput(inputs[i]); results[i] = p.calculateResult(); 
}

String and String Buffer

  • if you’re assembling strings inside a loop, you should think about a different approach, possibly involving StringBuffer.

Failing Gracefully

  • your code should catch java.lang.OutOfMemoryError. It is far better for you to catch OutOfMemoryErrors than for your host environment to catch them. You, at least, have a chance to do something reasonable—free up some memory and try again, or fail gracefully with a politely worded message to the user. The host environment is not likely to be so kind, and user perception of your application will be much worse.

Use Arrays Instead of Objects.

  • arrays are much faster as compared to vector and hashtable , if possible use simple array there you can save a lot of memory

  • Try to size the array.

  • Vector creates a new internal array and copies elements from the old array to the new array

  • Hashtable allocates new arrays and performs a computationally expensive operation called rehashing

  • Both Vector and Hashtable have constructors that allow you to specify the initial size of the collection. You should specify the initial size of these collections as accurately as possible.

Use Buffered I/O

  • do not read and write as a single byte at a time , read and write an whole array full of data.

Be Clean

  • free array or object once done with them

  • set array reference to null so that it can be garbage collected.

  • we can also call the gc : System.gc to release memory

  • close the network connections or inputStream once not required

  • the problem occurs if an exception is thrown while you’re trying to read data from the connection’s input stream. In this case, execution jumps down to the exception handler, and the input stream and connection are never closed

  • use finally block to close the connection

HttpConnection hc = null;
InputStream in = null; 
try { hc = (HttpConnection)Connector.open(url);
     in = hc.openInputStream(); 
     // Read data from in. 
     } catch (IOException ioe) {
      // Handle the exception. 
      } 
      finally {
       try { 
       if (in != null) in.close(); 
        if (hc != null) hc.close(); 
        } 
        catch (IOException ioe) {} }

Optmise the User Interface

  • if you display a spinning clock or a moving progress bar, your application will at least look like it’s still alive while it’s waiting for the network.

  • It’s important to remember that you are trying to optimize the perceived speed of your application, not the actual speed of the application.

Summary

  • Creating and destroying objects is expensive,

  • One common source of new objects is code that creates Strings. Consider optimizing String manipulation using StringBuffer or character arrays.

  • Similarly, you may be able to streamline code by using object arrays in place of Vectors or Hashtables.

  • Remember that performance is as much about perception as anything else; provide a responsive, active user interface and handle failures gracefully.

  • You can also optimize the delivery of your application in several ways.

  • First, partitioning the functionality of your application intelligently can reduce the runtime footprint of your application.

    .

REAL POST :

oracle.com/technetwork/java/chap10-159297.pdf