Writing Performance Effective Java Code
Based on my prior experience and/or learning's, here are few tips I suggest every Java programmer to follow for writing performance effective Java Code.
- Use ‘StringBuilder’ instead of String concatenation: Always prefer the usage of ‘StringBuilder’ when you have requirement of concatenating large number of string values.
- Do not prefer to use immutable class constructors; instead use static factory methods if available. [eg: use of String constructor class for literals. Instead prefer the usage of String literals.]
i.e. Prefer
String s1=”abc”; instead of String s1=new String(“abc”);
Use Integer.valueOf(String) instead of new Integer(String);
- Prefer the use of primitive types instead of boxed primitive or wrapper types:
Eg: Integer sum=0;
for(int i=0; i<1000; i++)
sum+=i;
The above program with wrapper
type is much slower than this one:
int sum=0;
for(int i=0; i<1000; i++)
sum+=i;
- Prefer the use of primitive data
comparisons to String value comparisons.
- In primitives, prefer this comparison order. i.e. use boolean, byte, char, short, int, long instead of ‘float’ and ‘double’ comparisons
- Minimize the usage of synchronization and synchronized utility classes in Java API’s wherever possible.
eg. Prefer use
of ‘StringBuilder’ to ‘StringBuffer’, ‘ArrayList’ to ‘Vector’, ‘HashMap’ to
‘Hashtable’ etc.
- Minimize the mutability of classes: Always declare the member variables or objects with least possible access specifier and make them ‘final’ when there is guarantee that it’s not changed.
- Try to have all the member variables or objects as ‘private’ unless other access specifier is required
- Make all the unchanged primitive variables ‘final’
- Make all the arrays or collections whose references should remain same as ‘final’
- Make all the methods ‘final’ when you are sure that the method definition should not be changed.
- Keep re-usable code in static final methods: If there is any business logic, or functionality which does not belong to any of your classes or entity, move the methods into a utility class and make all of methods static and final.
- Minimize the scope of local variables: Declare local variables only when it is used for first time. Do not declare them in the very beginning; and use it some where in the middle. By the time reader would have forgot the initial value of variable if any defined.
- Use static block initializers to initialize or construct the expensive objects instead of having them in the methods which gets called many times.
- Prefer the usage of interfaces to reflection: when you follow reflective way of instantiating your class i.e. (with use Class.forName(classname-to-load)), you
- Lose all benefits of compile-time type checking
- Suffer with slow performance in method invocation.
No comments:
Post a Comment