In Java, String, StringBuilder, and stringbuffer are often used to handle string manipulations.
The following table lists their similarities and differences:
|
String |
StringBuffer |
StringBuilder |
Whether it can be inherited |
No (final) |
No (final) |
No (final) |
Whether the length is variable |
Whether |
Is |
Is |
is thread safe |
---------- |
Is |
Whether |
Splicing efficiency |
Low |
In |
High |
In general, the use of String,stringbuilder more. Because the concatenation of strings rarely involves multi-threading, StringBuffer use less. Let's talk about the common use of string:
<span style= "FONT-SIZE:18PX;" >string S1 = "abc"; String s2 = s1 + "Def";</span>
This stitching method is inefficient. Because when you perform the second line of code, the actual operation is this:
New StringBuilder (string.valueof (S1)). Append ("Def"). ToString ();
Therefore, each time the stitching operation is performed, the system will first create a StringBuilder object. Creating the object itself consumes resources more.
Take a look at the concatenation of characters using StringBuilder:
<span style= "FONT-SIZE:18PX;" >stringbuilder StringBuilder = new StringBuilder () stringbuilder.append ("abc"); Stringbuilder.append ("Def");< /SPAN>
using the StringBuilder stitching string will only create the object once and then use the Append () method to stitch the characters continuously.
StringBuffer source and StringBuilder closer, splicing process is similar. However, the StringBuffer implementation should take into account the problem of thread synchronization, so the performance is less than StringBuilder.
Online people on the string, StringBuffer, striingbuilder splicing efficiency has done a small test, the efficiency gap between them is still very large. The following table is quoted from the reference example, String, StringBuffer, StringBuilder did 6 tests, each test completed 200,000 times stitching. And then calculate their average time-consuming.
Number |
String |
StringBuffer |
StringBuilder |
0 |
231232 |
17 |
14 |
1 |
233207 |
6 |
6 |
2 |
231294 |
8 |
6 |
3 |
235481 |
7 |
6 |
4 |
231987 |
9 |
6 |
5 |
230132 |
8 |
7 |
Average |
3 ' 52 " |
9.2 |
7.5 |
You can see that the efficiency of stringbuffer is much higher than string, and StringBuilder efficiency is higher stringbuffer more than 18%.
Summarize:
It is recommended to use StringBuilder, without regard to thread synchronization security, which involves frequent string operations, and it performs the most efficiently. To take into account thread synchronization, using StringBuffer, it can ensure that thread safety is maintained at a high level of efficiency. String "+" operation is very convenient, if not very involved in a lot of operations, using string is also a good choice.
Reference:
Small melon Cattle ramble about-string, StringBuffer, StringBuilder
The difference between String, StringBuilder and StringBuffer