Java中String和StringBuffer有什么区别?
String是否有最大长度限制?
Java中String和StringBuffer有什么区别?
String是否有最大长度限制?
虽然我明白这不是一个主要的区分因素,但我今天注意到StringBuffer(和StringBuilder)提供了一些String没有的有趣方法。
字符串是不可变的,这意味着当您对字符串执行操作时,实际上是创建了一个全新的字符串。
StringBuffer 是可变的,您可以将其附加到它并将其长度重置为0。
在实践中,编译器似乎在字符串连接出于性能原因时使用StringBuffer。
差异在于
String class is overriding toString(), equals(), hashCode() of Object class, but StringBuffer only overrides toString().
String s1 = new String("abc");
String s2 = new String("abc");
System.out.println(s1.equals(s2)); // output true
StringBuffer sb1 = new StringBuffer("abc");
StringBuffer sb2 = new StringBuffer("abc");
System.out.println(sb1.equals(sb2)); // output false
String class is both Serializable as well as Comparable, but StringBuffer is only Serializable.
Set<StringBuffer> set = new TreeSet<StringBuffer>();
set.add(sb1);
set.add(sb2);
System.out.println(set); // gives ClassCastException because there is no Comparison mechanism
We can create a String object with and without new operator, but StringBuffer object can only be created using new operator.
从性能上看,StringBuffer比String好得多;因为每次在String对象上应用连接时,都会创建新的String对象。
主要规则:String是不可变的,而StringBuffer是可变的
这里是编程实验,您可以得到性能差异
public class Test {
public static int LOOP_ITERATION= 100000;
public static void stringTest(){
long startTime = System.currentTimeMillis();
String string = "This";
for(int i=0;i<LOOP_ITERATION;i++){
string = string+"Yasir";
}
long endTime = System.currentTimeMillis();
System.out.println(endTime - startTime);
}
public static void stringBufferTest(){
long startTime = System.currentTimeMillis();
StringBuffer stringBuffer = new StringBuffer("This");
for(int i=0;i<LOOP_ITERATION;i++){
stringBuffer.append("Yasir");
}
long endTime = System.currentTimeMillis();
System.out.println(endTime - startTime);
}
public static void main(String []args){
stringTest()
stringBufferTest();
}
}
字符串的输出在我的机器上 14800
StringBuffer的输出在我的机器上 14