String, StringBuffer, StringBuilder的关系

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对象,会很慢,产生很多垃圾

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值