1.三者在执行速度方面的比较:StringBuilder > StringBuffer > String
2.String <(StringBuffer,StringBuilder)的原因
String:字符串常量
StringBuffer:字符串变量
StringBuilder:字符串变量
3.StringBuilder与 StringBuffer
StringBuilder:线程非安全的
StringBuffer:线程安全的
当我们在字符串缓冲去被多个线程使用是,JVM不能保证StringBuilder的操作是安全的,虽然他的速度最快,但是可以保证StringBuffer是可以正确操作的。当然大多数情况下就是我们是在单线程下进行的操作,所以大多数情况下是建议用StringBuilder而不用StringBuffer的,就是速度的原因。
对于三者使用的总结: 1.如果要操作少量的数据用 = String
2.单线程操作字符串缓冲区 下操作大量数据 = StringBuilder
3.多线程操作字符串缓冲区 下操作大量数据 = StringBuffer
参考https://www.cnblogs.com/A_ming/archive/2010/04/13/1711395.html
关于速度
http://blog.csdn.net/mad1989/article/details/26389541
public class StringTest {
public static String BASEINFO = "Mr.Y";
public static final int COUNT = 2000000;
/**
* 执行一项String赋值测试
*/
public static void doStringTest() {
String str = new String(BASEINFO);
long starttime = System.currentTimeMillis();
for (int i = 0; i < COUNT / 100; i++) {
str = str + "miss";
}
long endtime = System.currentTimeMillis();
System.out.println((endtime - starttime)
+ " millis has costed when used String.");
}
/**
* 执行一项StringBuffer赋值测试
*/
public static void doStringBufferTest() {
StringBuffer sb = new StringBuffer(BASEINFO);
long starttime = System.currentTimeMillis();
for (int i = 0; i < COUNT; i++) {
sb = sb.append("miss");
}
long endtime = System.currentTimeMillis();
System.out.println((endtime - starttime)
+ " millis has costed when used StringBuffer.");
}
/**
* 执行一项StringBuilder赋值测试
*/
public static void doStringBuilderTest() {
StringBuilder sb = new StringBuilder(BASEINFO);
long starttime = System.currentTimeMillis();
for (int i = 0; i < COUNT; i++) {
sb = sb.append("miss");
}
long endtime = System.currentTimeMillis();
System.out.println((endtime - starttime)
+ " millis has costed when used StringBuilder.");
}
/**
* 测试StringBuffer遍历赋值结果
*
* @param mlist
*/
public static void doStringBufferListTest(List<String> mlist) {
StringBuffer sb = new StringBuffer();
long starttime = System.currentTimeMillis();
for (String string : mlist) {
sb.append(string);
}
long endtime = System.currentTimeMillis();
System.out.println(sb.toString() + "buffer cost:"
+ (endtime - starttime) + " millis");
}
/**
* 测试StringBuilder迭代赋值结果
*
* @param mlist
*/
public static void doStringBuilderListTest(List<String> mlist) {
StringBuilder sb = new StringBuilder();
long starttime = System.currentTimeMillis();
for (Iterator<String> iterator = mlist.iterator(); iterator.hasNext();) {
sb.append(iterator.next());
}
long endtime = System.currentTimeMillis();
System.out.println(sb.toString() + "builder cost:"
+ (endtime - starttime) + " millis");
}
public static void main(String[] args) {
doStringTest();
doStringBufferTest();
doStringBuilderTest();
List<String> list = new ArrayList<String>();
list.add(" I ");
list.add(" like ");
list.add(" BeiJing ");
list.add(" tian ");
list.add(" an ");
list.add(" men ");
list.add(" . ");
doStringBufferListTest(list);
doStringBuilderListTest(list);
}
}