• java中字符串拼接 String 和 StringBuilder(StringBuffer)的使用


    字符串拼接是个常用的功能,经常性使用String做字符串拼接,当拼接次数多的时候,使用String方法会消耗大量的性能和时间,因为每次String拼接时都会建立一个新的对象,随着拼接次数的增多,性能消耗、时间消耗会大量增加,这个时候应该使用StringBuilder方法。

     1 public static void main(String[] args) {
     2         try {
     3             int count = 500;
     4 
     5             long begin = System.currentTimeMillis();
     6             testString(count);
     7             long end = System.currentTimeMillis();
     8             long time = end - begin;
     9             System.out.println("String 方法拼接"+count+"次消耗时间:" + time + "毫秒");
    10 
    11             begin = System.currentTimeMillis();
    12             testStringBuilder(count);
    13             end = System.currentTimeMillis();
    14             time = end - begin;
    15             System.out.println("StringBuilder 方法拼接"+count+"次消耗时间:" + time + "毫秒");
    16 
    17         } catch (Exception e) {
    18             e.printStackTrace();
    19         }
    20 
    21     }
    22 
    23     private static String testString(int count) {
    24         String result = "";
    25 
    26         for (int i = 0; i < count; i++) {
    27             result += "hello ";
    28         }
    29 
    30         return result;
    31     }
    32 
    33     private static String testStringBuilder(int count) {
    34         StringBuilder sb = new StringBuilder();
    35 
    36         for (int i = 0; i < count; i++) {
    37             sb.append("hello");
    38         }
    39 
    40         return sb.toString();
    41     }

    运行结果:

    String 方法拼接500次消耗时间:2毫秒
    StringBuilder 方法拼接500次消耗时间:0毫秒
    String 方法拼接50000次消耗时间:4973毫秒
    StringBuilder 方法拼接50000次消耗时间:3毫秒
  • 相关阅读:
    python爬虫之requests库
    python爬虫之urllib库
    fiddler配置及使用教程
    react中受控组件相关的warning
    Sublime Text 自动生成文件头部注释(版权信息):FileHeader 插件的使用
    手动安装sublime插件babel-sublime
    自定义组件 点击空白处隐藏
    pagination分页(支持首页,末页,跳转)
    vue打包以后,除了首页意外,其余页面是空白
    pm2踩过的坑
  • 原文地址:https://www.cnblogs.com/coderwood/p/4203030.html
Copyright © 2020-2023  润新知