zoukankan      html  css  js  c++  java
  • 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毫秒
  • 相关阅读:
    MySQL GTID复制Slave跳过错误事务Id以及复制排错问题总结
    Git基础命令整理
    原创-公司项目部署交付环境预检查shell脚本
    解决SecureCRT超时自动断开的问题
    Linux设置显示中文和设置字体
    高等代数4 线性方程组
    高等代数3 行列式
    高等代数2 向量组
    高等代数1 矩阵
    离散数学4 组合数学
  • 原文地址:https://www.cnblogs.com/coderwood/p/4203030.html
Copyright © 2011-2022 走看看