幾種拼接字串的效率問題

2021-09-22 22:04:27 字數 1422 閱讀 3513

public class test    

long end1 = system.currenttimemillis();

long time1 = end1 -start1;

system.out.println("用string+=拼接字串的時間"+time1);

long start2 = system.currenttimemillis();

string s2 = new string("hello");

for (long i = 0; i < n; i++)

long end2 = system.currenttimemillis();

long time2 = end2 -start2;

system.out.println("用string=string+拼接字串的時間"+time2);

long start3 = system.currenttimemillis();

string s3 = new string("hello");

for (long i = 0; i < n; i++)

long end3 = system.currenttimemillis();

long time3 = end3 -start3;

system.out.println("用string.concat拼接字串的時間"+time3);

long start4 = system.currenttimemillis();

stringbuffer s4 = new stringbuffer("hello");

for (long i = 0; i < n; i++)

long end4 = system.currenttimemillis();

long time4 = end4 -start4;

long start5 = system.currenttimemillis();

stringbuilder s5 = new stringbuilder("hello");

for (long i = 0; i < n; i++)

long end5 = system.currenttimemillis();

long time5 = end5 -start5;

system.out.println("end..."); }

}

貼出一組檢測資料如下:

用string+=拼接字串的時間27468

用string=string+拼接字串的時間25813

用string.concat拼接字串的時間12265

幾種拼接字串的效率問題

public class test long end1 system.currenttimemillis long time1 end1 start1 system.out.println 用string 拼接字串的時間 time1 long start2 system.currenttimemil...

幾種拼接字串的效率問題

拼接字串,大致有3個class可以用,他們是string,stringbuffer,stringbuilder,stringbuilder是1.5中來代替stringbuffer的。檢驗方法如下 public class test long end1 system.currenttimemillis...

c 字串拼接效率

1 對於少量固定的字串拼接,如string s a b c 系統會優化成s string.concat a b c 不會新建多個字串。如果寫成string s a s b s c 則會建立三個新的字串。可見,它和stringbuilder有著相似的效率,比用 的拼接方式高效,並且 易於閱讀。stri...