When the compiler sees
String s = "abc" + someint + somearray[index];
StringBuffer temp = new StringBuffer( ); temp.append( String.valueOf( "abc" ) ); temp.append( String.valueOf( someInt ) ); temp.append( String.valueOf( someArray[index] ); String s = temp.toString( );
So to optimize we have to bypass the automatic StringBuffer when possible. In this JAVA How-to, a snippet is given to replace a character at a specific position. An optimized version, using the StringBuffer would be:
public static String replaceCharAt(String s, int pos, char c) {
StringBuffer buf = new StringBuffer( s );
buf.setCharAt( pos, c );
return buf.toString( );
}
In the same How-to, a snippet about removing a character in a String can be optimized like:
public static String removeChar(String s, char c) {
StringBuffer r = new StringBuffer( s.length() );
r.setLength( s.length() );
int current = 0;
for (int i = 0; i < s.length(); i ++) {
char cur = s.charAt(i);
if (cur != c) r.setCharAt( current++, cur );
}
return r.toString();
}
The weak spot of the original method to remove a character is when the parameter s passed havee than 17 characters, the temporary StringBuffer created by the compiler will have to be extended. To optimize, simply rewrite the method using a StringBuffer with the correct size:
public static String removeCharAt(String s, int pos) {
StringBuffer buf = new StringBuffer( s.length() - 1 );
buf.append( s.substring(0,pos) ).append( s.substring(pos+1) );
return buf.toString();
}
The code
StringBuffer sb = new StringBuffer(300);
for (int i = 0; i < 100; i++) {
sb.append(i).append('\n');
}
StringBuilder sb = new StringBuilder(300);
for (int i = 0; i < 100; i++) {
sb.append(i).append('\n');
}
Written and compiled by Réal Gagnon ©1998-2011
[ home ]