关于何时使用,及效率
eg:
public static void main(String[] args) {
Long beginTime1 = System.nanoTime();
String str = "sdfsdf"+"sdfsfsf"+"sdfsdfsdf";
Long endTime1 = System.nanoTime();
Long beginTime2 = System.nanoTime();
StringBuffer sb = new StringBuffer();
sb.append("sdfsdf");
sb.append("sdfsfsf");
sb.append("sdfsdfsdf");
Long endTime2 = System.nanoTime();
Long beginTime3 = System.nanoTime();
StringBuilder sbl = new StringBuilder();
sbl.append("sdfsdf");
sbl.append("sdfsfsf");
sbl.append("sdfsdfsdf");
Long endTime3 = System.nanoTime();
System.out.println(endTime1 - beginTime1);
System.out.println(endTime2 - beginTime2);
System.out.println(endTime3 - beginTime3);
}
执行效率
一般情况下StringBuilder > StringBuffer>String
StringBuffer:线程安全,效率略低于StringBuilder,适用于全局变量
StringBuilder:一般情况下,效率最高,适用于局部变量