Java字符串拼接效率測(cè)試過(guò)程解析
測(cè)試代碼:
public class StringJoinTest { public static void main(String[] args) { int count = 10000; long begin, end, time; begin = System.currentTimeMillis(); testString(count); end = System.currentTimeMillis(); time = end - begin; System.out.println("拼接" + count + "次,String消耗時(shí)間:" + time + "毫秒"); begin = System.currentTimeMillis(); testStringBuffer(count); end = System.currentTimeMillis(); time = end - begin; System.out.println("拼接" + count + "次,StringBuffer消耗時(shí)間:" + time + "毫秒"); begin = System.currentTimeMillis(); testStringBuilder(count); end = System.currentTimeMillis(); time = end - begin; System.out.println("拼接" + count + "次,StringBuilder消耗時(shí)間:" + time + "毫秒"); } private static String testStringBuilder(int count) { StringBuilder tem = new StringBuilder(); for (int i = 0; i < count; i++) { tem.append("hello world!"); } return tem.toString(); } private static String testStringBuffer(int count) { StringBuffer tem = new StringBuffer(); for (int i = 0; i < count; i++) { tem.append("hello world!"); } return tem.toString(); } private static String testString(int count) { String tem = ""; for (int i = 0; i < count; i++) { tem += "hello world!"; } return tem; } }
測(cè)試結(jié)果:
結(jié)論:
在少量字符串拼接時(shí)還看不出差別,但隨著數(shù)量的增加,String+拼接效率顯著降低。在達(dá)到100萬(wàn)次,我本機(jī)電腦已經(jīng)無(wú)法執(zhí)行String+拼接了,StringBuilder效率略高于StringBuffer。所以在開(kāi)發(fā)過(guò)程中通常情況下推薦使用StringBuilder。
StringBuffer和StringBuilder的區(qū)別在于StringBuffer是線(xiàn)程安全的。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
JFileChooser實(shí)現(xiàn)對(duì)選定文件夾內(nèi)圖片自動(dòng)播放和暫停播放實(shí)例代碼
這篇文章主要介紹了JFileChooser實(shí)現(xiàn)對(duì)選定文件夾內(nèi)圖片自動(dòng)播放和暫停播放實(shí)例代碼,需要的朋友可以參考下2017-04-04Java并發(fā)工具之CountDownLatch使用詳解
這篇文章主要介紹了Java并發(fā)工具之CountDownLatch使用詳解,通過(guò)使用 CountDownLatch可以使當(dāng)前線(xiàn)程阻塞,等待其他線(xiàn)程完成給定任務(wù),可以類(lèi)比旅游團(tuán)導(dǎo)游要等待所有的游客到齊后才能去下一個(gè)景點(diǎn),需要的朋友可以參考下2023-12-12微信公眾號(hào)獲取access_token的方法實(shí)例分析
這篇文章主要介紹了微信公眾號(hào)獲取access_token的方法,結(jié)合實(shí)例形式分析了java實(shí)現(xiàn)微信公眾號(hào)獲取access_token的相關(guān)原理、實(shí)現(xiàn)方法及操作注意事項(xiàng),需要的朋友可以參考下2019-10-10Apache DolphinScheduler實(shí)現(xiàn)自動(dòng)化打包單機(jī)/集群部署詳解
這篇文章主要為大家介紹了Apache DolphinScheduler實(shí)現(xiàn)自動(dòng)化打包單機(jī)/集群部署詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-09-09詳解Java編程中if...else語(yǔ)句的嵌套寫(xiě)法
這篇文章主要介紹了Java編程中if...else語(yǔ)句的嵌套寫(xiě)法,是Java入門(mén)學(xué)習(xí)中的基礎(chǔ)知識(shí),需要的朋友可以參考下2015-11-11SpringBoot讀取自定義配置文件方式(properties,yaml)
這篇文章主要介紹了SpringBoot讀取自定義配置文件方式(properties,yaml),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07java socket接收保證能讀完數(shù)據(jù)的實(shí)例
這篇文章主要介紹了java socket接收保證能讀完數(shù)據(jù)的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-10-10