Java里面字符串拼接,估计是使用的最多的,经常使用的就是几种方式,谁的效率高呢:

1,直接使用“+”来拼接字符串

2,使用字符串自带的contact()方法

3,使用StringBuffer的append()和toString()方法

4,使用StringBuilder的append()和toString()方法

暂时就这么几个,若是再有的话,再继续比较。

下面看看,他们一起运行的时间占比截图
大师兄

使用的测试代码:

text
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
   private static final String TTM = "0|pr";
   public static void main(String[] args) {
      testStringContact();
   }

   private static void testStringContact() {
      String[] split = TTM.split("\\|");
      int length =split.length;
      while (true){
         String s = testAdd(split, length);
         String s1 = testStringBuilderAppend(split, length);
         String s2 = testStringBufferAppend(split, length);
         String s3 = testContact(split, length);
      }
   }

   private static String testContact(String[] split, int length) {
      String result = "";
      for (int i = 0; i < length; i++) {
         result = result.concat(split[i]);
      }
      return result;
   }

   private static String testStringBufferAppend(String[] split, int length) {
      StringBuffer stringBuffer = new StringBuffer();
      for (int i = 0; i < length; i++) {
         stringBuffer.append(split[i]);
      }
      return stringBuffer.toString();
   }

   private static String testStringBuilderAppend(String[] split, int length) {
      StringBuilder stringBuilder = new StringBuilder();
      for (int i = 0; i < length; i++) {
         stringBuilder.append(split[i]);
      }
      return stringBuilder.toString();
   }

   private static String testAdd(String[] split, int length) {
      String result = null;
      for (int i = 0; i < length; i++) {
         result +=split[i];
      }
      return result;
   }

有么有比这个builder还快的呢?

原文地址:https://blog.csdn.net/qq_27093465/article/details/92430589?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522168474993716782425192019%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=168474993716782425192019&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_ecpm_v1~rank_v31_ecpm-7-92430589-null-null.142^v87^insert_down1,239^v2^insert_chatgpt&utm_term=java%E4%BC%98%E5%8C%96