- Counting down (i.e. for (int i=n; i>0; i–)) is twice as fast as counting up: my machine can count down to 144 million in a second, but up to only 72 million.
- Calling Math.max(a,b) is 7 times slower than (a > b) ? a : b. This is the cost of a method call.
- Arrays are 15 to 30 times faster than Vectors. Hashtables are 2/3 as fast as Vectors.
- Use System.arraycopy(firstArray, 0, secondArray, 0, firstArray.length) method instead of iterating the first array and copying into second array.
- Use compound assignment operators (+=, -=, *=, and /=) instead of using normal operators.
- Ex: a = a+b takes longer time to execute when compared to a += b. In fact, these cause different Java byte codes to be generated.
- Eliminate unnecessary code in the loops and you should avoid declaring variables unnecessarily within loops.
- Use int instead of other primitive types because operations performed on int primitives generally execute faster than for any other primitive type supported by Java, so you should use int values whenever possible; char and short values are promoted to int automatically before arithmetic operations.
- Use notify() instead of notifyAll(), notify will execute faster than notifyAll().
- When joining couple of Stings use StringBuffer instead of String.
- Don’t try to convert Strings to upper or lower case for String comparison.
- In the String Class prefer charAt() method instead of startsWith() method. From performance perspective, startWith() makes quite a few comparisons preparing itself to compare it’s prefix with another string.
- Don’ t initialize the public instance variable in constructor if they already initialized outside the constructor. Because all public initialized instance variables are again initialized in constructor by default.
- Vector provides the following methods to insert elements.
addElementAt( e, index)
- 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.
- 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.
One thought on “Tips to fallow while doing JAVA code”