Preface
I recently wrote something that may have considered string splicing and thought of several methods, but the performance is unknown, so let’s test it below. Let’s take a look at the detailed introduction together.
Sample code
public class Test { List<String> list = new ArrayList<>(); @Before public void init(){ IntStream.range(0, 100000).forEach((index) -> { list.add("str" + index); }); } @org.junit.Test public void test1() { String ss = ""; long startTime = System.currentTimeMillis(); for (String s: list) { ss += s; } System.out.println(System.currentTimeMillis() - startTime); } @org.junit.Test public void test2() { String ss = ""; long startTime = System.currentTimeMillis(); for (String s: list) { ss=ss.concat(s); } System.out.println(System.currentTimeMillis() - startTime); } @org.junit.Test public void test3() { StringBuilder ss = new StringBuilder(); long startTime = System.currentTimeMillis(); for (String s: list) { ss.append(s); } System.out.println(System.currentTimeMillis() - startTime); } @org.junit.Test public void test4() { long startTime = System.currentTimeMillis(); StringUtils.join(list); System.out.println(System.currentTimeMillis() - startTime); } @org.junit.Test public void test5() { StringBuffer ss = new StringBuffer(); long startTime = System.currentTimeMillis(); for (String s : list) { ss.append(s); } System.out.println(System.currentTimeMillis() - startTime); }}The first type: 33809
The second type: 8851
The third type: 6
The fourth type: 12
The fifth type: 7
Performance: StringBuilder>StringBuffer>StringUtils.join>concat>+
Then analyze it from the source code level
StringBuilder:
Each string splicing just expands the internal char array and produces only a final string, so this is the most efficient
StringBuffer:
Compared with StringBuilder, there is only one more synchronized, so the difference is not big in a single threaded case.
StringUtils.join:
You can see that it is still implemented internally with StringBuilder, but each loop has an extra separator to judge, so it is a little slower, but not much, and it is an order of magnitude in time.
concat:
It can be seen that each connection will generate a string, so the efficiency is very low
+:
Because it is an overloaded operator, the source code cannot be found, but the efficiency is the lowest according to the results
Summarize
The above is the entire content of this article. I hope that the content of this article has certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support to Wulin.com.