1.StringBuffer is synchronized, but StringBuilder not. So StringBuilder is faster than StringBuffer.
1) code: append empty string
public static void main(String[] args) {
int N = 5000000;
long t;
StringBuffer sBuffer = new StringBuffer();
t = System.currentTimeMillis();
int i = 0;
while (i++ < N)
sBuffer.append("");
System.out.println("sBuffer time: " + (System.currentTimeMillis() - t));
StringBuilder sBuilder = new StringBuilder();
t = System.currentTimeMillis();
i = 0;
while (i++ < N)
sBuilder.append("");
System.out.println("sBuilder time: " + (System.currentTimeMillis() - t));
}
Output:
sBuffer time: 227
sBuilder time: 19
2) append a space char: sBuffer.append(" ")
sBuffer time: 403
sBuilder time: 144
3)initialize Buffer size first, append space char:
StringBuffer sBuffer = new StringBuffer(N);
StringBuilder sBuilder = new StringBuilder(N);
Output:
sBuffer time: 225
sBuilder time: 19
In conclusion, StringBuilder is faster than StringBuffer many times. When buffer memory is been allocated dynamic in running time, Array.copy() time will larger than synchronized time, it lead to difference of time be smaller.
2.create a new StringBuilder object is expensive, we should always reuse the object.
code:
long
t = System.currentTimeMillis();int
i = 0, N = 5000000;while
(i++ < N) {StringBuilder sb = new StringBuilder();
sb.append(
"test for something");sb.append(
"test for something2" + i);sb.append(
" test for something3" + i);sb.append(
"test for something4" + i);a = sb.toString();
}
System.out.println( "in the loop time: " + (System.currentTimeMillis() - t));
t = System.currentTimeMillis();
StringBuilder sb = new StringBuilder();
i = 0;
while
(i++ < N) {sb.setLength(0);
sb.append(
"test for something");sb.append(
"test for something2" + i);sb.append(
" test for something3" + i);sb.append(
"test for something4" + i);}
System.out.println( " out the loop time: " + (System.currentTimeMillis() - t)
Output:
in the loop time: 4725
out the loop time: 2816