SimpleDateFormatformatter=newSimpleDateFormat("dd-MMM-yyyy HH:mm:ss:SSS"); Stringstring=""; StringBuilderstringBuilder=newStringBuilder(); System.out.println("time before string+string "+formatter.format(newDate())); for (inti=0; i < 1000000; i++) { string = string + "1"; } System.out.println("time after string+string "+formatter.format(newDate())); System.out.println("time before stringBuilder.append "+formatter.format(newDate())); for (inti=0; i < 1000000; i++) { stringBuilder.append("1"); } System.out.println("time after stringBuilder.append "+formatter.format(newDate()));
试验结果:前者需要5分多钟,后者是毫秒级的。只知道速度有差异,没想到会差这么多,被惊到了!
1 2 3 4
time before string+string 29-五月-2018 22:33:35:347 time after string+string 29-五月-2018 22:38:53:943 time before stringBuilder.append 29-五月-2018 22:38:53:944 time after stringBuilder.append 29-五月-2018 22:38:53:955