作者 | 老坛酸菜WH

来源 | https://www.cnblogs.com/twzheng/p/5923642.html

> 字符串拼接一般使用“+”,但是“+”不能满足大批量数据的处理,Java中有以下五种方法处理字符串拼接,各有优缺点,程序开发应选择合适的方法实现。

  1. 加号 “+”

  2. String contact() 方法

  3. StringUtils.join() 方法

  4. StringBuffer append() 方法

  5. StringBuilder append() 方法

> 经过简单的程序测试,从执行100次到90万次的时间开销如下表:

由此可以看出:

  1. 方法1 加号 “+” 拼接 和 方法2 String contact() 方法 适用于小数据量的操作,代码简洁方便,加号“+” 更符合我们的编码和阅读习惯;

  2. 方法3 StringUtils.join() 方法 适用于将ArrayList转换成字符串,就算90万条数据也只需68ms,可以省掉循环读取ArrayList的代码;

  3. 方法4 StringBuffer append() 方法 和 方法5 StringBuilder append() 方法 其实他们的本质是一样的,都是继承自AbstractStringBuilder,效率最高,大批量的数据处理最好选择这两种方法。

  4. 方法1 加号 “+” 拼接 和 方法2 String contact() 方法 的时间和空间成本都很高(分析在本文末尾),不能用来做批量数据的处理。

如果您正在学习Spring Boot,推荐一个连载多年还在继续更新的免费教程:http://blog.didispace.com/spring-boot-learning-2x/

> 源代码,供参考

package cnblogs.twzheng.lab2;/*** @author Tan Wenzheng**/
import java.util.ArrayList;
import java.util.List;import org.apache.commons.lang3.StringUtils;public class TestString {private static final int max = 100;public void testPlus() {System.out.println(">>> testPlus() <<<");String str = "";long start = System.currentTimeMillis();for (int i = 0; i < max; i++) {str = str + "a";}long end = System.currentTimeMillis();long cost = end - start;System.out.println("   {str + \"a\"} cost=" + cost + " ms");}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<String> list = new ArrayList<String>();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.* <p>* 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.* <p>* Let <i>n</i> be the length of this character sequence just prior to* execution of the {@code append} method. Then the character at* index <i>k</i> in the new character sequence is equal to the character* at index <i>k</i> in the old character sequence, if <i>k</i> is less* than <i>n</i>; otherwise, it is equal to the character at index* <i>k-n</i> 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 codeif (minimumCapacity - value.length > 0)expandCapacity(minimumCapacity);}/*** This implements the expansion semantics of ensureCapacity with no* size check or synchronization.*/void expandCapacity(int minimumCapacity) {int newCapacity = value.length * 2 + 2;if (newCapacity - minimumCapacity < 0)newCapacity = minimumCapacity;if (newCapacity < 0) {if (minimumCapacity < 0) // overflowthrow new OutOfMemoryError();newCapacity = Integer.MAX_VALUE;}value = Arrays.copyOf(value, newCapacity);}
  1. 字符串的加号“+” 方法, 虽然编译器对其做了优化,使用StringBuilder的append方法进行追加,但是每循环一次都会创建一个StringBuilder对象,且都会调用toString方法转换成字符串,所以开销很大。如果您正在学习Spring Cloud,推荐一个连载多年还在继续更新的免费教程:https://blog.didispace.com/spring-cloud-learning/

注:执行一次字符串“+”,相当于 str = new StringBuilder(str).append("a").toString();

  1. 本文开头的地方统计了时间开销,根据上述分析再想想空间的开销。常说拿空间换时间,反过来是不是拿时间换到了空间呢,但是在这里,其实时间是消耗在了重复的不必要的工作上(生成新的对象,toString方法),所以对大批量数据做处理时,加号“+” 和 contact 方法绝对不能用,时间和空间成本都很高。

往期推荐

程序员的“鱿鱼游戏”,你能活到第几关?

大名鼎鼎的 OceanBase 居然在买Star !?

支付宝员工因绩效3.25B被辞退,员工告上法院,结果来了!

为什么 JSP 还没有被淘汰?

理工男有多香?一张桌子、一条视频,股价狂涨13.51%!网友:我看到了乔布斯!

技术交流群

最近有很多人问,有没有读者交流群,想知道怎么加入。加入方式很简单,有兴趣的同学,只需要点击下方卡片,回复“加群“,即可免费加入我们的高质量技术交流群!

点击阅读原文,送你免费Spring Boot教程!

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

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

    字符串拼接一般使用"+",但是"+"不能满足大批量数据的处理,Java中有以下五种方法处理字符串拼接,各有优缺点,程序开发应选择合适的方法实现. 加号 &quo ...

  2. 最优雅的Java字符串拼接是哪种方式?

    title shortTitle category tag description head 最优雅的Java字符串拼接是哪种方式? Java字符串拼接 Java核心 数组&字符串 Java程 ...

  3. java 字符串拼接_JAVA字符串拼接常见方法汇总

    字符串的拼接,常使用到的大概有4种方式: 1.直接使用"+"号 2.使用String的concat方法 3.使用StringBuilder的append方法 4.使用StringB ...

  4. java字符串拼接常用方式

    方式一:+ "+",是java操作运算符比较常用的,也是简单直接的一种方式. String aa = "魅言倾馨";String bb = "子非我鱼 ...

  5. 理解Java字符串常量池与intern()方法

    理解Java字符串常量池与intern()方法 阅读目录 Java内存区域 两种创建方式在内存中的区别 解释开头的例子 intern()方法 参考资料 String s1 = "Hello& ...

  6. C\C++\Java字符串拼接比较

    C\C++\Java字符串拼接比较: 昨天买好小米盒子,自己折腾了一会然后就教会老妈怎么玩,怎么看还珠格格之后,我闲来无事,突然想起了上次一个项目处理字符串遇到的性能问题,然后就仔细考虑了一下,越考虑 ...

  7. [js] 字符串拼接有哪些方式?哪种性能好?

    [js] 字符串拼接有哪些方式?哪种性能好? 1.使用 + 号 2.es6模板字符串,以反引号( ` )标识 3.concat 4.数组方法join性能最好的是连接: + 继续补充:Array.pro ...

  8. Java字符串拼接“+“

    Java字符串拼接"+" 当字符串之间使用 + 号拼接的时候,系统底层会自动创建一个StringBuilder对象,然后再调用其append方法完成拼接,拼接后,再调用其toStr ...

  9. HashMap遍历 (四种方法+7种实现方式)

    HashMap遍历 (四种方法+7种实现方式) HashMap遍历从大的方向来说,可分为一下4类: 1.迭代器(Iterator)方式: 2.foreach方式: 3.lambda表达式(JDK 1. ...

最新文章

  1. 哈佛终身教授:年轻人如何做科研?
  2. @Profile-根据不同环境注入bean
  3. BZOJ3473:字符串(后缀数组,主席树,二分,ST表)
  4. java获取系统电量_android操作系统怎么获得电量
  5. 2020年网易校招提前批JAVA岗笔试第一题
  6. lua-nginx-module directives 中文版
  7. 中文正则表达式初步使用
  8. 俺是如何在3个月内写出博士论文的?
  9. 01.轮播图之四 :imageViews(2 或者 3 个imageview) 轮播
  10. Python 基于项目自动生成 requirements.txt 文件
  11. 天线的布局、基本术语、种类、隔离度设计要求介绍
  12. OpenGL ——安装和环境配置
  13. 海明贴近度matlab,Matlab学习系列23.-模糊聚类分析原理及实现.docx
  14. HDU 6287 口算训练
  15. 【宝藏系列】如何解决word选中文字按backspace无法删除的问题
  16. matlab emd功率谱密度,【脑电信号分类】脑电信号提取PSD功率谱密度特征
  17. 今天,过了27年后,IE浏览器停用了
  18. vue中使用require动态获取图片地址
  19. “usermod:UID‘0‘already exists”
  20. to_csv ()出现中文乱码

热门文章

  1. Disucz!高级幻灯片制作
  2. Chrome OS与平板电脑才是珠联璧合
  3. 用投资的观点学习编程
  4. 如何汉化DNN--中文语言包的使用
  5. linux /etc/fstab 挂载列表 简介
  6. linux touch命令 新建文件 更新文件时间
  7. python 字符串前面加u,r,b,f的含义
  8. python 信号模块 signal
  9. Nmap/Netcat/Hping3工具对比
  10. linux tail命令详解