Translate

Wednesday, November 14, 2012

Java Performance Tuning-2



1st Rule for Avoiding objects creation:

Why?
  
Avoid object creation

Lots of objects in memory means GC does lots of work
•Program slows down when GC starts
•Creating object costs time and CPU effort for application
•Reuse objects where possible

Pool management

•Most container (e.g. Vector) objects could be reused rather than created and thrown away




Canonical zing objects















Keyword, ‗final‘

•Use the final modifier on variable to create immutable internally accessible object





Auto-Boxing/Unboxing



Object-Creation was made every time we wrap primitive by boxing


2nd Rule KNOWING STRING BETTER

•String is the Object mostly used in the application

•Overlook the String

•The software may have the poor performance


Compile-Time Initialization



Knowing String Better

Runtime String Initialization


Knowing String Better
To test if String is empty



If two strings have the same length



If two strings have different length



Knowing String Better

Knowing String Better

 Intern String

•Normally, string can be created by two ways:
•By new String(…)
•String s = new String(“This is a string literal.”);
•By String Literals
•String s = “This is a string literal.”;
•Create Strings by new String(…)
•JVM always allocate a new memory address for each new String created even if they are the same.


String a = new String(“This is a string literal”);
String b = new String(“This is a string litera”);










By using reference, identity comparison is fast






  
The char array

String x = "abcdefghijklmn";
for (int i =0; i < loop; i++)
{
if (x.charAt(5) == 'x')
{
}                                 Takes 281ms
}
------------------------------------------------
String x = "abcdefghijklmn";
char y[] = x.toCharArray();
for (int i =0; i < loop; i++)
{
if (y[5] == 'x')
{
}                                  Takes 156ms
}


you can see loop optimization next post

No comments: