String在JAVA中是不可改变的常量
每次对String的更改其实都是产生了一个新的String对象,这会产生大量的垃圾。 而StringBuffer和StringBuilder是这个问题的应对方案。
String内部由一个char[]储存数据
// Java program to demonstrate difference between
// String, StringBuilder and StringBuffer
// Main class
class GFG {
// Method 1
// Concatenates to String
public static void concat1(String s1)
{
s1 = s1 + "forgeeks";
}
// Method 2
// Concatenates to StringBuilder
public static void concat2(StringBuilder s2)
{
s2.append("forgeeks");
}
// Method 3
// Concatenates to StringBuffer
public static void concat3(StringBuffer s3)
{
s3.append("forgeeks");
}
// Method 4
// Main driver method
public static void main(String[] args)
{
// Custom input string
// String 1
String s1 = "Geeks";
// Calling above defined method
concat1(s1);
// s1 is not changed
System.out.println("String: " + s1);
// String 1
StringBuilder s2 = new StringBuilder("Geeks");
// Calling above defined method
concat2(s2);
// s2 is changed
System.out.println("StringBuilder: " + s2);
// String 3
StringBuffer s3 = new StringBuffer("Geeks");
// Calling above defined method
concat3(s3);
// s3 is changed
System.out.println("StringBuffer: " + s3);
}
}
String: Geeks
StringBuilder: Geeksforgeeks
StringBuffer: Geeksforgeeks
方法1无法修改String引用的字面量,方法2可以实现,因为StringBuilder是可变的,方法3 StringBuffer是线程安全的
- If a string is going to remain constant throughout the program, then use the String class object because a String object is immutable.
- If a string can change (for example: lots of logic and operations in the construction of the string) and will only be accessed from a single thread, using a StringBuilder is good enough.
- If a string can change and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous, so you have thread-safety.
为什么有些时候StringBuilder比String += 快
String += 被编译器编译后使用StringBuilder.append实现
当在循环中使用+=时,每次循环要产生一个StringBuilder实例,和一个新的String对象,会很慢,产生很多垃圾