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。所以在開發(fā)過(guò)程中通常情況下推薦使用StringBuilder。
StringBuffer和StringBuilder的區(qū)別在于StringBuffer是線程安全的。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. html清除浮動(dòng)的6種方法示例2. phpstudy apache開啟ssi使用詳解3. JavaScript中常見的幾種獲取元素的方式4. ASP.NET MVC使用異步Action的方法5. Xml簡(jiǎn)介_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理6. jsp實(shí)現(xiàn)登錄驗(yàn)證的過(guò)濾器7. jsp文件下載功能實(shí)現(xiàn)代碼8. uni-app結(jié)合.NET 7實(shí)現(xiàn)微信小程序訂閱消息推送9. AJAX的跨域問(wèn)題解決方案10. ajax實(shí)現(xiàn)頁(yè)面的局部加載
