久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術(shù)文章
文章詳情頁

Java字符串拼接效率測試過程解析

瀏覽:84日期:2022-09-01 16:44:46

測試代碼:

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; }}

測試結(jié)果:

Java字符串拼接效率測試過程解析

Java字符串拼接效率測試過程解析

Java字符串拼接效率測試過程解析

結(jié)論:

在少量字符串拼接時(shí)還看不出差別,但隨著數(shù)量的增加,String+拼接效率顯著降低。在達(dá)到100萬次,我本機(jī)電腦已經(jīng)無法執(zhí)行String+拼接了,StringBuilder效率略高于StringBuffer。所以在開發(fā)過程中通常情況下推薦使用StringBuilder。

StringBuffer和StringBuilder的區(qū)別在于StringBuffer是線程安全的。

Java字符串拼接效率測試過程解析

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。

標(biāo)簽: Java
相關(guān)文章:
主站蜘蛛池模板: 韩城市| 嘉鱼县| 兰西县| 页游| 垫江县| 鹤岗市| 博野县| 酉阳| 罗甸县| 石阡县| 青州市| 金坛市| 怀化市| 大石桥市| 景宁| 合川市| 长泰县| 鄯善县| 台南市| 恩施市| 河源市| 迁西县| 安溪县| 富宁县| 阳曲县| 翁牛特旗| 平舆县| 保靖县| 青神县| 西畴县| 内黄县| 祁东县| 柘城县| 贺州市| 宜宾市| 铜陵市| 碌曲县| 凭祥市| 衢州市| 德兴市| 塔城市|