/**
* 字符串拼接
*/
public class StringAddDemo {
public static void main(String[] args){
testStringAdd();
testConcat();
testStringBuilder();
testStringBuffer();
//+:676
//concat:243
//StringBuilder:9
//StringBuffer:1
}
public static void testStringAdd(){
String s = "";
long begin = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
s = s + i;
}
long end = System.currentTimeMillis();
System.out.println("+:" + (end-begin));
}
//连接
public static void testConcat(){
String s = "";
long begin = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
s = s.concat(String.valueOf(i));
}
long end = System.currentTimeMillis();
System.out.println("concat:" + (end-begin));
}
//synchronization
public static void testStringBuffer(){
StringBuffer sb = new StringBuffer();
long begin = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
sb.append(i);
}
sb.toString();
long end = System.currentTimeMillis();
System.out.println("StringBuffer:" + (end-begin));
}
public static void testStringBuilder(){
StringBuilder sb = new StringBuilder();
long begin = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
sb.append(i);
}
sb.toString();
long end = System.currentTimeMillis();
System.out.println("StringBuilder:" + (end-begin));
}
}