Java字符串拼接的五种方法,哪种性能最好?

文章对比了Java中的String、StringBuffer和StringBuilder在进行字符串连接操作时的性能差异,通过测试显示,StringBuilder和StringBuffer由于避免了频繁创建新String对象,性能优于String.concat(),尤其在大量操作时差距明显。
摘要由CSDN通过智能技术生成

public void testConcat() {

System.out.println(“>>> testConcat() <<<”);

String str = “”;

long start = System.currentTimeMillis();

for (int i = 0; i < max; i++) {

str = str.concat(“a”);

}

long end = System.currentTimeMillis();

long cost = end - start;

System.out.println("   {str.concat(“a”)} cost=" + cost + " ms");

}

public void testJoin() {

System.out.println(“>>> testJoin() <<<”);

long start = System.currentTimeMillis();

List list = new ArrayList();

for (int i = 0; i < max; i++) {

list.add(“a”);

}

long end1 = System.currentTimeMillis();

long cost1 = end1 - start;

StringUtils.join(list, “”);

long end = System.currentTimeMillis();

long cost = end - end1;

System.out.println("   {list.add(“a”)} cost1=" + cost1 + " ms");

System.out.println("   {StringUtils.join(list, “”)} cost=" + cost

+ " ms");

}

public void testStringBuffer() {

System.out.println(“>>> testStringBuffer() <<<”);

long start = System.currentTimeMillis();

StringBuffer strBuffer = new StringBuffer();

for (int i = 0; i < max; i++) {

strBuffer.append(“a”);

}

strBuffer.toString();

long end = System.currentTimeMillis();

long cost = end - start;

System.out.println("   {strBuffer.append(“a”)} cost=" + cost + " ms");

}

public void testStringBuilder() {

System.out.println(“>>> testStringBuilder() <<<”);

long start = System.currentTimeMillis();

StringBuilder strBuilder = new StringBuilder();

for (int i = 0; i < max; i++) {

strBuilder.append(“a”);

}

strBuilder.toString();

long end = System.currentTimeMillis();

long cost = end - start;

System.out

.println("   {strBuilder.append(“a”)} cost=" + cost + " ms");

}

}

> 测试结果:

  1. 执行100次, private static final int max = 100;

testPlus() <<<

{str + “a”} cost=0 ms

testConcat() <<<

{str.concat(“a”)} cost=0 ms

testJoin() <<<

{list.add(“a”)} cost1=0 ms

{StringUtils.join(list, “”)} cost=20 ms

testStringBuffer() <<<

{strBuffer.append(“a”)} cost=0 ms

testStringBuilder() <<<

{strBuilder.append(“a”)} cost=0 ms

  1. 执行1000次, private static final int max = 1000;

testPlus() <<<

{str + “a”} cost=10 ms

testConcat() <<<

{str.concat(“a”)} cost=0 ms

testJoin() <<<

{list.add(“a”)} cost1=0 ms

{StringUtils.join(list, “”)} cost=20 ms

testStringBuffer() <<<

{strBuffer.append(“a”)} cost=0 ms

testStringBuilder() <<<

{strBuilder.append(“a”)} cost=0 ms

  1. 执行1万次, private static final int max = 10000;

testPlus() <<<

{str + “a”} cost=150 ms

testConcat() <<<

{str.concat(“a”)} cost=70 ms

testJoin() <<<

{list.add(“a”)} cost1=0 ms

{StringUtils.join(list, “”)} cost=30 ms

testStringBuffer() <<<

{strBuffer.append(“a”)} cost=0 ms

testStringBuilder() <<<

{strBuilder.append(“a”)} cost=0 ms

  1. 执行10万次, private static final int max = 100000;

testPlus() <<<

{str + “a”} cost=4198 ms

testConcat() <<<

{str.concat(“a”)} cost=1862 ms

testJoin() <<<

{list.add(“a”)} cost1=21 ms

{StringUtils.join(list, “”)} cost=49 ms

testStringBuffer() <<<

{strBuffer.append(“a”)} cost=10 ms

testStringBuilder() <<<

{strBuilder.append(“a”)} cost=10 ms

  1. 执行20万次, private static final int max = 200000;

testPlus() <<<

{str + “a”} cost=17196 ms

testConcat() <<<

{str.concat(“a”)} cost=7653 ms

testJoin() <<<

{list.add(“a”)} cost1=20 ms

{StringUtils.join(list, “”)} cost=51 ms

testStringBuffer() <<<

{strBuffer.append(“a”)} cost=20 ms

testStringBuilder() <<<

{strBuilder.append(“a”)} cost=16 ms

  1. 执行50万次, private static final int max = 500000;

testPlus() <<<

{str + “a”} cost=124693 ms

testConcat() <<<

{str.concat(“a”)} cost=49439 ms

testJoin() <<<

{list.add(“a”)} cost1=21 ms

{StringUtils.join(list, “”)} cost=50 ms

testStringBuffer() <<<

{strBuffer.append(“a”)} cost=20 ms

testStringBuilder() <<<

{strBuilder.append(“a”)} cost=10 ms

  1. 执行90万次, private static final int max = 900000;

testPlus() <<<

{str + “a”} cost=456739 ms

testConcat() <<<

{str.concat(“a”)} cost=186252 ms

testJoin() <<<

{list.add(“a”)} cost1=20 ms

{StringUtils.join(list, “”)} cost=68 ms

testStringBuffer() <<<

{strBuffer.append(“a”)} cost=30 ms

testStringBuilder() <<<

{strBuilder.append(“a”)} cost=24 ms

> 查看源代码,以及简单分析

String contact 和 StringBuffer,StringBuilder 的源代码都可以在Java库里找到,有空可以研究研究。

  1. 其实每次调用contact()方法就是一次数组的拷贝,虽然在内存中是处理都是原子性操作,速度非常快,但是,最后的return语句会创建一个新String对象,限制了concat方法的速度。

public String concat(String str) {

int otherLen = str.length();

if (otherLen == 0) {

return this;

}

int len = value.length;

char buf[] = Arrays.copyOf(value, len + otherLen);

str.getChars(buf, len);

return new String(buf, true);

}

  1. StringBuffer 和 StringBuilder 的append方法都继承自AbstractStringBuilder,整个逻辑都只做字符数组的加长,拷贝,到最后也不会创建新的String对象,所以速度很快,完成拼接处理后在程序中用strBuffer.toString()来得到最终的字符串。

/**

* Appends the specified string to this character sequence.

* The characters of the {@code String} argument are appended, in

* order, increasing the length of this sequence by the length of the

* argument. If {@code str} is {@code null}, then the four

* characters {@code “null”} are appended.

* Let n be the length of this character sequence just prior to

* execution of the {@code append} method. Then the character at

* index k in the new character sequence is equal to the character

* at index k in the old character sequence, if k is less

* than n; otherwise, it is equal to the character at index

k-n in the argument {@code str}.

* @param   str   a string.

* @return  a reference to this object.

*/

public AbstractStringBuilder append(String str) {

if (str == null) str = “null”;

int len = str.length();

ensureCapacityInternal(count + len);

str.getChars(0, len, value, count);

count += len;

return this;

}

/**

* This method has the same contract as ensureCapacity, but is

* never synchronized.

*/

private void ensureCapacityInternal(int minimumCapacity) {

// overflow-conscious code

if (minimumCapacity - value.length > 0)

expandCapacity(minimumCapacity);

}

/**

* This implements the expansion semantics of ensureCapacity with no

* size check or synchronization.

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数Java工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

如果你觉得这些内容对你有帮助,可以扫码获取!!(备注Java获取)

img

知其然不知其所以然,大厂常问面试技术如何复习?

1、热门面试题及答案大全

面试前做足功夫,让你面试成功率提升一截,这里一份热门350道一线互联网常问面试题及答案助你拿offer

2、多线程、高并发、缓存入门到实战项目pdf书籍

3、文中提到面试题答案整理

4、Java核心知识面试宝典

覆盖了JVM 、JAVA集合、JAVA多线程并发、JAVA基础、Spring原理、微服务、Netty与RPC、网络、日志、Zookeeper、Kafka、RabbitMQ、Hbase、MongoDB 、Cassandra、设计模式、负载均衡、数据库、一致性算法 、JAVA算法、数据结构、算法、分布式缓存、Hadoop、Spark、Storm的大量技术点且讲解的非常深入


《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!
37645658)]

[外链图片转存中…(img-kMstU5Ld-1713137645658)]

3、文中提到面试题答案整理

[外链图片转存中…(img-4VZjd295-1713137645658)]

4、Java核心知识面试宝典

覆盖了JVM 、JAVA集合、JAVA多线程并发、JAVA基础、Spring原理、微服务、Netty与RPC、网络、日志、Zookeeper、Kafka、RabbitMQ、Hbase、MongoDB 、Cassandra、设计模式、负载均衡、数据库、一致性算法 、JAVA算法、数据结构、算法、分布式缓存、Hadoop、Spark、Storm的大量技术点且讲解的非常深入

[外链图片转存中…(img-S2SZTQ8p-1713137645658)]

[外链图片转存中…(img-CsOS4Sbu-1713137645659)]

[外链图片转存中…(img-0Xqazvwg-1713137645659)]
《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!

  • 25
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值