String:字符串常量,非线程安全
StringBuilder:字符串变量,非线程安全
StringBuffer:字符串变量,线程安全
下面自己写的测试效率的代码
package com.jaws.string;
import com.jaws.util.TimeUtil;
public class KnowStringClient {
public static void main(String[] args) {
String name = "I am String A";
String age = ",i am twenty senven year old" ;
String job = ",my job is Java Coder.";
String fors = ".";
Long before = 0L , after=0L;
//Test for Spring
before = TimeUtil.getNowLong();
String strTest = name+age+job;
for (int i = 0; i < 5000; i++) {
strTest+=fors;
}
//System.out.println(strTest);
after = TimeUtil.getNowLong();
System.out.println("String: "+TimeUtil.getDiffLong(before, after));
//Test for SpringBuilder
before = TimeUtil.getNowLong();
StringBuilder builderTest = new StringBuilder();
builderTest.append(name);
builderTest.append(age);
builderTest.append(job);
for (int i = 0; i < 5000; i++) {
builderTest.append(fors);
}
System.out.println(builderTest.toString());
after = TimeUtil.getNowLong();
System.out.println("StringBuilder: "+TimeUtil.getDiffLong(before, after));
//Test for SpringBuffer
before = TimeUtil.getNowLong();
StringBuffer bufferTest = new StringBuffer();
bufferTest.append(name);
bufferTest.append(age);
bufferTest.append(job);
for (int i = 0; i < 5000; i++) {
bufferTest.append(fors);
}
System.out.println(bufferTest.toString());
after = TimeUtil.getNowLong();
System.out.println("StringBuffer: "+TimeUtil.getDiffLong(before, after));
}
}
执行结果:
I am String A,i am twenty senven year old,my job is Java Coder........................
String: 31
I am String A,i am twenty senven year old,my job is Java Coder.......................
StringBuilder: 0
I am String A,i am twenty senven year old,my job is Java Coder..........................
StringBuffer: 15
从执行结果看在单线程测试效率情况,StringBuilder>StringBuffer>String,用String拼接花了31毫秒,StringBuilder执行太快没能显示出差值,
StringBuffer花了15毫秒,测试多次StringBuffer也有多次没能显示出差值,三个对象的执行效率都是非常快,所以我觉得在日常开发中重点注
意的是线程安全的问题,如果一个字符串可能被多个线程修改需使用StringBuffer对象。
以上是小弟的见解,如果有对的地方,望指出,乐意接受批评