浅谈String、StringBuffer和StringBuilder之间的区别

  package com.scg.springcloudordercenter.controller;

  /**

  * @author gf

  * @date 2023/2/21

  */

  public class StringTest {

  public static void main(String[] args) {

  long startTime;

  long endTime;

  String str1 = "";

  StringBuffer str2 = new StringBuffer("");

  StringBuilder str3 = new StringBuilder("");

  // 1.拼接str1,计算String所耗时间

  startTime = System.currentTimeMillis();

  for(int i= 1;i<=10000;i++){

  str1 += i;

  }

  endTime = System.currentTimeMillis();

  System.out.println("String所耗时间为:" + (endTime-startTime) + "毫秒");

  // 2.拼接str2,计算StringBuffer所耗时间

  startTime = System.currentTimeMillis();

  for(int i= 1;i<=10000;i++){

  str2.append(i);

  }

  endTime = System.currentTimeMillis();

  System.out.println("StringBuffer所耗时间为:" + (endTime-startTime) + "毫秒");

  // 3.拼接str3,计算StringBuilder所耗时间

  startTime = System.currentTimeMillis();

  for(int i= 1;i<=10000;i++){

  str3.append(i);

  }

  endTime = System.currentTimeMillis();

  System.out.println("StringBuilder所耗时间为:" + (endTime-startTime) + "毫秒");

  }

  }