首先大多情况下的效率:StringBuilder>StringBuffer>String
原因:1.sting:String类的声明是:public final是不可变的,每次改变值都会在内存中创建一个空间(对象)来保存,改变的多了对性能有影响。
String S1 = “This is only a” + “ simple” + “ test”;(快,但是换成对象就会很慢)
StringBuffer Sb = new StringBuilder(“This is only a”).append(“ simple”).append(“ test”);
StringBuffer Sb = new StringBuilder(“This is only a”).append(“ simple”).append(“ test”);
2. tringBuffer大部分方法都是synchronized,线程安全的,所以单线程的话用stingbulider,多线程就只能用stringbuffer。
String S1 = “This is only a” + “ simple” + “ test”;
StringBuffer Sb = new StringBuilder(“This is only a”).append(“ simple”).append(“ test”);
StringBuffer Sb = new StringBuilder(“This is only a”).append(“ simple”).append(“ test”);