Java字符串拼接效率測試過程解析
測試代碼:
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消耗時間:" + time + "毫秒");
begin = System.currentTimeMillis();
testStringBuffer(count);
end = System.currentTimeMillis();
time = end - begin;
System.out.println("拼接" + count + "次,StringBuffer消耗時間:" + time + "毫秒");
begin = System.currentTimeMillis();
testStringBuilder(count);
end = System.currentTimeMillis();
time = end - begin;
System.out.println("拼接" + count + "次,StringBuilder消耗時間:" + 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é)果:



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

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
JFileChooser實現(xiàn)對選定文件夾內(nèi)圖片自動播放和暫停播放實例代碼
這篇文章主要介紹了JFileChooser實現(xiàn)對選定文件夾內(nèi)圖片自動播放和暫停播放實例代碼,需要的朋友可以參考下2017-04-04
Java并發(fā)工具之CountDownLatch使用詳解
這篇文章主要介紹了Java并發(fā)工具之CountDownLatch使用詳解,通過使用 CountDownLatch可以使當(dāng)前線程阻塞,等待其他線程完成給定任務(wù),可以類比旅游團(tuán)導(dǎo)游要等待所有的游客到齊后才能去下一個景點,需要的朋友可以參考下2023-12-12
Apache DolphinScheduler實現(xiàn)自動化打包單機(jī)/集群部署詳解
這篇文章主要為大家介紹了Apache DolphinScheduler實現(xiàn)自動化打包單機(jī)/集群部署詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-09-09
SpringBoot讀取自定義配置文件方式(properties,yaml)
這篇文章主要介紹了SpringBoot讀取自定義配置文件方式(properties,yaml),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07
java socket接收保證能讀完數(shù)據(jù)的實例
這篇文章主要介紹了java socket接收保證能讀完數(shù)據(jù)的實例,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10

