认识String、StringBuilder、StringBuffer的区别

本文通过实验证明了在单线程环境下,使用StringBuilder比String更高效,而StringBuffer则用于多线程环境以确保线程安全性。测试结果显示,String拼接耗时31毫秒,StringBuilder几乎不增加任何额外时间,StringBuffer耗时15毫秒。
摘要由CSDN通过智能技术生成

String:字符串常量,非线程安全

StringBuilder:字符串变量,非线程安全

StringBuffer:字符串变量,线程安全

下面自己写的测试效率的代码

package com.jaws.string;

import com.jaws.util.TimeUtil;

public class KnowStringClient {
public static void main(String[] args) {
String name = "I am String A";
String age = ",i am twenty senven year old" ;
String job = ",my job is Java Coder.";
String fors = ".";
Long before = 0L , after=0L;
//Test for Spring
before = TimeUtil.getNowLong();
String strTest = name+age+job;
for (int i = 0; i < 5000; i++) {
strTest+=fors;
}
//System.out.println(strTest);
after = TimeUtil.getNowLong();
System.out.println("String: "+TimeUtil.getDiffLong(before, after));
//Test for SpringBuilder
before = TimeUtil.getNowLong();
StringBuilder builderTest = new StringBuilder();
builderTest.append(name);
builderTest.append(age);
builderTest.append(job);
for (int i = 0; i < 5000; i++) {
builderTest.append(fors);
}
System.out.println(builderTest.toString());
after = TimeUtil.getNowLong();
System.out.println("StringBuilder: "+TimeUtil.getDiffLong(before, after));
//Test for SpringBuffer
before = TimeUtil.getNowLong();
StringBuffer bufferTest = new StringBuffer();
bufferTest.append(name);
bufferTest.append(age);
bufferTest.append(job);
for (int i = 0; i < 5000; i++) {
bufferTest.append(fors);
}
System.out.println(bufferTest.toString());
after = TimeUtil.getNowLong();
System.out.println("StringBuffer: "+TimeUtil.getDiffLong(before, after));
}
}


执行结果:

I am String A,i am twenty senven year old,my job is Java Coder........................

String: 31

I am String A,i am twenty senven year old,my job is Java Coder.......................

StringBuilder: 0

I am String A,i am twenty senven year old,my job is Java Coder..........................

StringBuffer: 15

从执行结果看在单线程测试效率情况,StringBuilder>StringBuffer>String,用String拼接花了31毫秒,StringBuilder执行太快没能显示出差值,

StringBuffer花了15毫秒,测试多次StringBuffer也有多次没能显示出差值,三个对象的执行效率都是非常快,所以我觉得在日常开发中重点注

意的是线程安全的问题,如果一个字符串可能被多个线程修改需使用StringBuffer对象。


以上是小弟的见解,如果有对的地方,望指出,乐意接受批评

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值