Tuesday, May 7, 2013

String literal can be replaced by a character literal

The single character string literal can be replaced by a character literal to improve performance.

Example:


Given two functions:
public static String concatString(String cs) {
    return "hello" + cs + "world";
}

public static String concatChar(char cc) {
    return "hello" + cc + "world";
}
after examination of the bytecode it boils down to two AbstractStringBuilder.append(String) vs.AbstractStringBuilder.append(char).
Both methods invoke AbstractStringBuilder.expandCapacity(int)) which will allocate a new char[]eventually and System.arraycopy the old content first.
Afterwards AbstractStringBuilder.append(char) just has to put the given char in the array whereas AbstractStringBuilder.append(String) has to check a few constraints and calls String.getChars(int, int, char[], int) which does another System.arraycopy of the appended string.


Trial:



package kondal.performance;

public class StringTest {

public static void main(String[] args) {

long start = System.currentTimeMillis();

StringBuffer message1 = new StringBuffer("Hello world");
for (int i = 0; i < 1000000; i++) {
message1.append("Program");
message1.append("!");
}
long diff = (System.currentTimeMillis() - start);
System.out.println("Totat time(string) in ms:" + diff);


long start2 = System.currentTimeMillis();

StringBuffer message2 = new StringBuffer("Hello world");
for (int i = 0; i < 1000000; i++) {
message2.append("Program");
message2.append('!');
}
long diff2 = (System.currentTimeMillis() - start2);
System.out.println("Totat time(Char) in ms:" + diff2);

}
}


Results:
Totat time(string) in ms:154
Totat time(Char) in ms:116






1 comment: