关于JAVA 8 是否需要StringBuilder来拼接字符串的思考

来源:互联网 发布:手机期货软件排行 编辑:程序博客网 时间:2024/05/16 09:52

关于JAVA 8 是否需要StringBuilder来拼接字符串的思考

  • 最近看到一片文章说JAVA 8已经不需要使用StringBuilder来拼接字符串了,使用+的效率也会非常高,文章链接 http://www.codeceo.com/article/why-java8-not-use-stringbuilder.html 本篇博文就对该文章的说法进行一个讨论

  • 测试代码如下

import org.apache.commons.lang3.StringUtils;public class StringConcatTest {    public static void main(String[] args) {        System.out.println("Time cost for add: " + testAdd());        System.out.println("Time cost for append: " + testAppend());        System.out.println("Time cost for join: " + testJoin());    }    /**     * 测试使用+连接字符串     */    private static long testAdd() {        String a = "1";        long currentTime1 = System.currentTimeMillis();        for (int i = 1; i < 100000; i++) {            a = a + 1;        }        long currentTime2 = System.currentTimeMillis();        return currentTime2 - currentTime1;    }    /**     * 测试使用StringBuilder     */    private static long testAppend() {        StringBuilder stringBuilder = new StringBuilder();        long currentTime1 = System.currentTimeMillis();        for (int i = 0; i < 100000; i++) {            stringBuilder.append("1");        }        String s = stringBuilder.toString();        long currentTime2 = System.currentTimeMillis();        return currentTime2 - currentTime1;    }    /**     * 测试StringUtils.join     */    private static long testJoin(){        String a = "1";        long currentTime1 = System.currentTimeMillis();        for (int i = 1; i < 100000; i++) {            a = StringUtils.join(a,"1");        }        long currentTime2 = System.currentTimeMillis();        return currentTime2 - currentTime1;    }}
  • 测试代码输出如下

Time cost for add: 2537
Time cost for append: 3
Time cost for join: 3560

  • 结果分析

  • 从测试结果来看,在for循环中使用StringBuilder的append方法运行时间比使用+要快一个量级。这是为什么呢?——java 8中确实使用了StringBuilder来进行字符串的拼接,但是在for循环中,每次的+都会重新new StringBuilder,这个分析字节码指令可以清楚地看出 。

  • 使用StringUtils.join方法,同样运行时间非常慢,查看StringUtils.join的源码可以发现其每次也是new StringBuilder 。

  • 结论

  • http://www.codeceo.com/article/why-java8-not-use-stringbuilder.html 文章的说法不能说是错的——因为java 8 确实使用了StringBuilder来优化字符串变量的“后缀”操作;但是该文章却有标题党误导之嫌。

  • 在java 8 中使用for循环对字符串变量进行“后缀”操作仍然要使用StringBuilder,同时为了提高性能,建议在new StringBuilder时设置一个适当的长度,避免StringBuilder在“后缀”期间的扩容导致性能问题。

阅读全文
0 0