Efficiency comparison of five methods of splicing strings in Java
preface
Recently, I wrote something. I may consider string splicing and think of several methods, but I don't know the performance, so let's test it. I won't say much. Let's take a look at the detailed introduction together.
Sample code
First: 33809
Second: 8851
Third: 6
Fourth: 12
Fifth: 7
Performance: StringBuilder > StringBuffer > stringutils join>concat>+
Then analyze from the source level
StringBuilder:
Each string splicing only expands the internal char array and produces only one final string, so this method is the most efficient
StringBuffer:
Compared with StringBuilder, it only adds an additional synchronized, so it is not much different in the case of single thread
StringUtils. join:
You can see that it is still implemented by StringBuilder, but there are more separators in each cycle, so it is a little slow, but not much. In terms of time, it is an order of magnitude
concat:
It can be seen that each connection generates a string, so the efficiency is very low
+:
Because it is an overloaded operator, the source code cannot be found, but from the result, the efficiency is the lowest
summary
The above is the whole content of this article. I hope the content of this article has a certain reference value for your study or work. If you have any questions, you can leave a message. Thank you for your support for programming tips.