Java 5種字串拼接方式效能比較。
阿新 • • 發佈:2019-01-02
最近寫一個東東,可能會考慮到字串拼接,想了幾種方法,但對效能未知,於是用Junit寫了個單元測試。
程式碼如下:
- import java.util.ArrayList;
- import java.util.List;
- import org.apache.commons.lang.StringUtils;
- import org.junit.Test;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- publicclass TestString {
- privatefinal Logger logger = LoggerFactory.getLogger(
- @Test
- publicvoid testPlus() {
- String s = "";
- long ts = System.currentTimeMillis();
- for (int i = 0; i < 10000; i++) {
- s = s + String.valueOf(i);
- }
- long te = System.currentTimeMillis();
- logger.info("+ cost {} ms", te - ts);
- }
- @Test
- publicvoid testConcat() {
- String s = "";
- long ts = System.currentTimeMillis();
- for (int i = 0; i < 10000; i++) {
- s = s.concat(String.valueOf(i));
- }
- long te = System.currentTimeMillis();
- logger.info("concat cost {} ms", te - ts);
- }
- @Test
- publicvoid testJoin() {
- List<String> list =
- long ts = System.currentTimeMillis();
- for (int i = 0; i < 10000; i++) {
- list.add(String.valueOf(i));
- }
- StringUtils.join(list, "");
- long te = System.currentTimeMillis();
- logger.info("StringUtils.join cost {} ms", te - ts);
- }
- @Test
- publicvoid testStringBuffer() {
- StringBuffer sb = new StringBuffer();
- long ts = System.currentTimeMillis();
- for (int i = 0; i < 10000; i++) {
- sb.append(String.valueOf(i));
- }
- sb.toString();
- long te = System.currentTimeMillis();
- logger.info("StringBuffer cost {} ms", te - ts);
- }
- @Test
- publicvoid testStringBuilder() {
- StringBuilder sb = new StringBuilder();
- long ts = System.currentTimeMillis();
- for (int i = 0; i < 100000; i++) {
- sb.append(String.valueOf(i));
- }
- sb.toString();
- long te = System.currentTimeMillis();
- logger.info("StringBuilder cost {} ms", te - ts);
- }
- }
執行結果如下:
11:00:22,359 INFO TestString:23 - + cost 1828 ms
11:00:22,921 INFO TestString:34 - concat cost 562 ms
11:00:22,937 INFO TestString:46 - StringUtils.join cost 16 ms
11:00:22,968 INFO TestString:58 - StringBuffer cost 31 ms
11:00:23,031 INFO TestString:70 - StringBuilder cost 63 ms
要特別注意的是:
StringBuilder 迴圈的次數是其它的10倍,如果是一樣,那麼返回 0,可見StringBuilder 的速度之快。
總結:
用+的方式效率最差,concat由於是內部機制實現,比+的方式好了不少。
Join 和 StringBuffer,相差不大,Join方式要快些,可見這種JavaScript中快速拼接字串的方式在Java中也非常適用。
StringBuilder 的速度最快,但其有執行緒安全的問題,而且只有JDK5支援。