String StringBuilder StringBuffer "..." 4种的效率

本文通过实验对比了Java中不同字符串拼接方式的性能表现,包括直接拼接、使用StringBuilder、StringBuffer及String对象的方式,并提供了详细的测试代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

"..." +"..."       直接字面值的操作最快,因为 jvm 直接将其解释为 1个字符串

String 对象     的操作 比较耗费时间,

StringBuilder 还可以,非线程安全的

StringBuffer  还行,线程安全,比 StringBuilder 慢点,

 

大多数情况下,效率上:

"..." + "..."      >      StringBuilder      >      StringBuffer      >      String对象+String对象

 

测试类:

package test;

public class StringAddTest {
	private final static int repeatCount = 10000000;

	public void testStringDirect() {
		long begin = System.currentTimeMillis();
		for (int i = 0; i < repeatCount; i++) {
			String s = "abc" + "_opq_" + "xyz";
		}
		long over = System.currentTimeMillis();
		System.out.println("\"...\"+\"...\" 直接相加:" + (over - begin) + " millseconds ");
	}

	public void testStringBuffer() {
		long begin = System.currentTimeMillis();
		for (int i = 0; i < repeatCount; i++) {
			StringBuffer s = new StringBuffer();
			s.append("abc").append("_opq_").append("xyz");
		}
		long over = System.currentTimeMillis();
		System.out.println("StringBuffer 的 append() : " + (over - begin) + " millseconds ");
	}

	public void testStringBuilder() {
		long begin = System.currentTimeMillis();
		for (int i = 0; i < repeatCount; i++) {
			StringBuilder s = new StringBuilder();
			s.append("abc").append("_opq_").append("xyz");
		}
		long over = System.currentTimeMillis();
		System.out.println("StringBuilder 的 append() : " + (over - begin) + " millseconds ");
	}

	public void testStringObject() {
		long begin = System.currentTimeMillis();
		for (int i = 0; i < repeatCount; i++) {
			String s1 = "abc";
			String s2 = "_opq_";
			String s3 = "xyz";
			String s = s1 + s2 + s3;
		}
		long over = System.currentTimeMillis();
		System.out.println("String 对象 相加, 直接相加:" + (over - begin) + " millseconds ");
	}

	public static void main(String[] args) {
		StringAddTest st = new StringAddTest();
		st.testStringDirect();
		st.testStringBuffer();
		st.testStringBuilder();
		st.testStringObject();
	}
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值