Java字符串拼接效率測(cè)試過程解析
測(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萬次,我本機(jī)電腦已經(jīng)無法執(zhí)行String+拼接了,StringBuilder效率略高于StringBuffer。所以在開發(fā)過程中通常情況下推薦使用StringBuilder。
StringBuffer和StringBuilder的區(qū)別在于StringBuffer是線程安全的。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. ASP新手必備的基礎(chǔ)知識(shí)2. asp文件用什么軟件編輯3. CentOS郵箱服務(wù)器搭建系列——SMTP服務(wù)器的構(gòu)建( Postfix )4. js實(shí)現(xiàn)計(jì)算器功能5. golang中json小談之字符串轉(zhuǎn)浮點(diǎn)數(shù)的操作6. 通過IEAD+Maven快速搭建SSM項(xiàng)目的過程(Spring + Spring MVC + Mybatis)7. 利用CSS制作3D動(dòng)畫8. IDEA 2020.1.2 安裝教程附破解教程詳解9. Vue axios獲取token臨時(shí)令牌封裝案例10. JS中6個(gè)對(duì)象數(shù)組去重的方法

網(wǎng)公網(wǎng)安備