Java Programming Tips For Improving Code Performance (1)
In the end after the project is completed people spends thousands of dollars trying to buy some code optimization tools and then spend more money tracing the code and fixing the performance issues.
Here are few tips which if you follow while developing the code, it will reduce the money required to be spent on Optimization techniques, particularly useful for writing server side applications.
Java Tips 1
In the JSP pages, while sending out HTML code, don't write out every string as soon as it is created. If possible try to join multiple strings and send them in one go.
Java Tips 2
When joining couple of Stings use StringBuffer instead of String. Instead of writing
String str= "Welcome"+ "to" + "our" + "site";
Write it as
StringBuffer sb = new StringBuffer(50);
sb.append("Welcome");
sb.append("To");
sb.append("our");
sb.append("site");
If you know the Max Length of the String Buffer initially then use the number. For Example in the above scenario, the initial length of the StringBuffer is set to 50. This saves lot of over head since when length of the StringBuffer needs to be increased, then StringBuffer has to allocate new Character array with larger capacity, copy all the old contents into new array and discard the old array (during GC).
To avoid this over head declare the approximate size of StringBuffer initially. Also don't over allocate. Memory is precious at runtime.
Java Tips 3
Don't try to convert Strings to upper or lower case for String comparison. For example do not do,
str1 =a.toUpperCase();
str2 = b.toUpperCase();
boolean b = str1.equals(str2);
Instead use,
boolean bool =a.equalsIgnoreCase(b);
Again do not use equalsIgnoreCase() if equals() can be used. It adds another level of comparison while performing String comparison.
Java Tips 4
For converting String to bytes do not use method getBytes(). While handling HTTP strings most of the times its normal ASCII characters. For example do not use
bytes[] b= s.getBytes()
getBytes() method can handle any character encoding. But that power is not required for HTTP transactions most of the times. You can create you own method for handling only ASCII characters,
public static void mySimpleTokenizer(String s, String delimiter)
{
String sub = null;
int i =0;
int j =s.indexOf(delimiter); // First substring
while( j >= 0)
{
sub = s.substring(i,j);
i = j + 1;
j = s.indexOf(delimiter, i); // Rest of substrings
}
sub = s.substring(i); // Last substring
}
Next you can use this method as
byte[] b =getAsciiBytes(s);
Java Tips 5
For converting bytes to String, do not use the String
String s= new String (bytebuf);
Instead declare it as
String s= new String (bytebuf, 0);
This method works only for ASCII data, but the performance is really good. In HTTP protocol most of the times we deal with with only ASCII data.
Note : Although this method is deprecated, it might be a while before this method is totally removed, unless alternative comes for ASCII only data.
Java Tips 6
StringTokenizer is one of the most popularly used function in Java. It really gives the flexibility of parsing Strings with parsing capability of multiple string length delimiter. For example it can parse Strings separated by "bqr" as delimiter as follows,
StringTokenizer st =new StringTokenizer(myStr, "bqr");
But then there's always overhead during this operation. Since this has to compare each character, if it belongs in the set of delimiters.
Instead you can you this method, if Strings need to be delimited only by a single character,
public static void mySimpleTokenizer(String s, String delimiter)
{
String sub = null;
int i =0;
int j =s.indexOf(delimiter); // First substring
while( j >= 0) {
sub = s.substring(i,j);
i = j + 1;
j = s.indexOf(delimiter, i); // Rest of substrings
}
sub = s.substring(i); // Last substring
}
Our Tests reveal that the above method works almost 4 times faster than StringTokenizer, because of less overhead. But use this method with caution, since you might be loosing maintainability of your program.
Java Tips 7
Don't repeat the same function in conditional statements. For Example instead of writing
for (int i=0 ; i < s.length; i++) {
charc c =s.charAt(i);
}
Write it as ,
int j =str.length();
for (int i =0 ; i < j; i++) {
charc c =s.charAt(i);
}
Doing this you have removed a Extra overhead on Conditional Statement.
Java Tips 8
In the String Class prefer charAt() method instead of startsWith() method. String class provides this method to decide if the String starts starts with given Sub string. From performance perspective, startWith() makes quite a few comparisons preparing itself to compare it's prefix with another string.
So instead of writing,
if (s.startsWith("a") ) {
// Do something here
}
write it as,
if ("a" == s.charAt(0) ) {
// Do something here
}
Java Tips 9
Instead of writing,
String s ="a";
s += "b";
s += "c";
declare it as,
String s="a" + "b" + "c";
Since compiler is intelligent enough to replace above string with with
String s = "abc"
instead of creating new String object and appending them together in different steps.
Java Tips 10
Don't create objects unless required. For example do not declare
Date myDate =new Date();
if (requiredCondition) {
// usemyDate
}
Instead declare the Date object inside the if condition, so that it is not initialized if the required Condition is false. So declare the code as,
if (requiredCondition){
Date myDate =new Date();
// use myDate
}
Article source: http://ezine.softbath.net/computer/Java-Programming-Tips-For-Improving-Code-Performance-1--488.php
