温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java字符串拼接效率的测试

发布时间:2020-07-27 14:02:50 来源:亿速云 阅读:169 作者:小猪 栏目:编程语言

这篇文章主要讲解了Java字符串拼接效率的测试,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。

测试代码:

public class StringJoinTest {
  public static void main(String[] args) {
    int count = 10000;
    long begin, end, time;
    begin = System.currentTimeMillis();
    testString(count);
    end = System.currentTimeMillis();
    time = end - begin;
    System.out.println("拼接" + count + "次,String消耗时间:" + time + "毫秒");

    begin = System.currentTimeMillis();
    testStringBuffer(count);
    end = System.currentTimeMillis();
    time = end - begin;
    System.out.println("拼接" + count + "次,StringBuffer消耗时间:" + time + "毫秒");

    begin = System.currentTimeMillis();
    testStringBuilder(count);
    end = System.currentTimeMillis();
    time = end - begin;
    System.out.println("拼接" + count + "次,StringBuilder消耗时间:" + time + "毫秒");
  }

  private static String testStringBuilder(int count) {
    StringBuilder tem = new StringBuilder();
    for (int i = 0; i < count; i++) {
      tem.append("hello world!");
    }
    return tem.toString();
  }

  private static String testStringBuffer(int count) {
    StringBuffer tem = new StringBuffer();
    for (int i = 0; i < count; i++) {
      tem.append("hello world!");
    }
    return tem.toString();
  }

  private static String testString(int count) {
    String tem = "";
    for (int i = 0; i < count; i++) {
      tem += "hello world!";
    }
    return tem;
  }
}

测试结果:

Java字符串拼接效率的测试

Java字符串拼接效率的测试

Java字符串拼接效率的测试

结论:

  在少量字符串拼接时还看不出差别,但随着数量的增加,String+拼接效率显著降低。在达到100万次,我本机电脑已经无法执行String+拼接了,StringBuilder效率略高于StringBuffer。所以在开发过程中通常情况下推荐使用StringBuilder。

  StringBuffer和StringBuilder的区别在于StringBuffer是线程安全的。

Java字符串拼接效率的测试

看完上述内容,是不是对Java字符串拼接效率的测试有进一步的了解,如果还想学习更多内容,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI