| |
|
|
| |
|
|
|
|
|
|
|
Java Programming Tips For Improving Code Performance (2)
Java Tips 11
Do not declare the objects twice. For example in the following code snippet,
public class x{ privateVector v = new Vector(); public x() { v = new Vector(); } }
The compiler generates the following code for the Constructor,
public x() { v = new Vector(); v = new Vector(); }
By default anything initialized as public variables, the code for initialization is moved to constructor. So if you have initialized the public variable outside the default constructor , then do not initialize it inside the Constructor. So declare the code as,
public classx { privateVector v; public x() { v = new Vector(); } }
Java Tips 12
In the conditional statements, the conditions are evaluated in the order they are placed. For example if we declare as,
if (cond1 | | cond2){ // Do some operation }
then if the "cond1" is true, then "cond2" is never evaluated. It is compared only if "cond1" is false. Always try to take advantage of this one. For instructions which require more processing time, place them at the end. For Example declare it as,
boolean editmode = curStats1&& curStatus2; if (editMode ||getDataStatusFromDataBase()) { // do some operation }
In the above statement getDataStatusFromDataBase() is not called if edit Mode is true.
Java Tips 13
For Large Scale enterprise applications, it is common to add new Features and remove old features. if possible, if the old feature codes are never going to be used, then remove the old code. Don't try to place old code in,
if (lfOldFeatureRequired){ // Old Code. }
this makes the code larger and takes more maintenance time. Also It makes its lower to load the class at runtime.
Java Tips 14
Vector provides the following methods to insert elements. addElementAt( e, index) addElement (e) add(e) add(index, e)
Out of these try to avoid using methods, addElementAt( e, index) and add(index, e). The way these methods work is , all the elements are moved down between the insertion point and the end of the vector, making space for the new Element. The same works for deleting element at a Particular index. If possible, if these features are required, then try to use a different Data Structure if possible.
Java Tips 15
If the approximate size of the Vector is know initially then use it. Instead of declaring Vector as, Vector v = newVector(); declare it as, Vector v = new Vector(40); or Vector v = new Vector(40,25);
This method indicates initial capacity of Vector is 40 and increment by 25 elements per expansion.
The way the Vector is expanded is, a new Vector of double the size of currentVector is created, all the Elements in the old Vector is copied to the new Vector and then the old Vector is discarded. (During GC). This has major effect on performance.
So if the initial size of the Vector is known, use it. Same goes for the size of Hashtable and related Data structures.
Java Tips 16
Avoid using the Enumeration class. The way Enumeration class is used is,
for(Enumeration enum = v.elements(); enum.hasMoreElements() ) { s = (String)enum.nextElement(); // Do SomeOperation }
In this code, enum.hasMoreElements() takes lot of processing time. Also for enum.nextElement() , enumeration class has to do lot of processing internally like incrementing the internal Counter etc.
Instead for retrieving elements from Vector, here is the preferred way,
int size = v.size(); for (int i = 0; i< size; i++) { s = (String)v.elementAt(i); // Do SomeOperation }
Java Tips 17
If the code is executing in a SingleThread, then use ArrayList instead of Vector. All the methods in Vector are Synchronized. For example for the following methods,
public Object elementAt( int index) { return elementData [ index ]; }
In the Vector class, the elementAt() method explicitly verifies that the internal array index does not fall out of bounds. Methods in ArrayList leaves the task to user and are not Synchronized. This makes the execution faster.
Java Tips 18
Couple of times it becomes necessary in code to retrieve element at a particular position in the Vector and then remove that Element. Code for this one would be, e = v.elementAt(index); v.removeElementAt (index);
In such a scenario, use the following code e =v.remove(index);
This returns element at index position and then removes that element from Vector. This saves call to elementAt() method.
Java Tips 19
In Hashtable couple of times we try to get Element with particular key and if it does not exist, then we try to create new Element and insert that Element into Hashtable. Sometimes code is written as,
if( htable.containsKey(keyCode) ) { return htable.get(keyCode); } else { MyData md = createNewData(keyCode); htable.put ( keyCode, md); return md; }
Here, we made performance overhead by calling these two methods on the same Hashtable,containsKey() and get(). Both these methods do the same thing, except containsKey() returns true/false and get()returns the actual Element. If the Hashtable is of considerable size then the overhead is high. Instead write the code as follows, if ( (md = (MyData)htable.get (keyCode) != null ){ return md; } else { // insert New Element into Hashtable here. }
Java Tips 20
Cache Data as much as possible both on the Server and Client side as much as possible. For example do no try to get Data from Database every time which is hardly going to change for a long time. Either store it in local text or properties files or cache it for a pre defined interval once it is read from Database.
Java Tips 21
InetAddress.getHostAddress() has a lot of new operations. It creates a lot of intermediate strings to return the host address. Avoid it, if possible.
Java Tips 22
java.util.Date has some performance problems, particularly with internationalization. If you frequently print out the current time as something other than the (long ms-since-epoch) that it is usually represented as, you may be able to cache your representation of the current time and then create a separate thread to update that representation every N seconds (N depends on how accurately you need to represent the current time). You could also delay converting the time until a client needs it, and the current representation is known to be stale.
Java Tips 23
Avoid java.lang.String.hashCode() . If the String's length exceeds 16 characters, hashCode() samples only a portion of the String. So if the places that a set of Strings differ in don't get sampled you can see lots of similar hash values. This can turn your hash tables into linked lists!
Java Tips 24
Good Design is very important for any project. In most applications, good performance comes from getting the architecture right. Using the right data structures for the problem you're solving is a lot more important than tweaking String operations. Thread architecture is also important. (Try to avoid wait/notify operations--they can cause a lot of lock contention in some VMs.) And of course you should use caching for your most expensive operations.
Java Tips 25
This is one of the most common mistakes. A lot of people do something like the following:
debug("Debug Comment: " + var1 + var1 + "Current Value"); public static void debug(String s) { System.err.println(s); }
Then they think that they've turned off debugging overhead. Nope! If there are enough debugging statements, you can see a lot of time spent in creating new strings to evaluate "Debug Comment: " + var1 + var1 + "Current Value", which is then tossed after calling debug .
View more articles about about [Java Programming Tips For Improving Code Performance (2)]
|
|
|
|