Do you know the difference between String, StringBuffer and StringBuilder

String

Official explanation: The String class is an immutable class, that is, once a String object is created, the sequence of characters contained in the object cannot be changed until the object is destroyed.

That is to say, when we String a = "111"; a = "222", instead of re-assigning the instance object in the original heap, a new object was generated and pointed a to "222", and The previous instance object "111" still exists, waiting to be garbage collected.

StringBuffer与StringBuilder

These two are basically similar, are variable string objects, the main difference is whether the thread is safe.

to sum up

Finally, to quote the summary and related comments under the rookie tutorial:

  • String length is not variable, while StringBuffer and StringBuilder are variable in length
  • StringBuffer is thread safe, while StringBuilder thread is not safe
  • StringBuilder is fast
  • There is basically no applicable scenario for stringbuffer, you should choose to use stringbuiler in all cases

In addition, regarding thread safety, even if you really encounter such a scene, unfortunately, I am afraid that you still have 99.99 ... 99% of the cases, there is no need to choose stringbuffer, because the thread safety of stringbuffer is only to ensure that jvm does not throw If it goes down abnormally, it can be executed smoothly. It does not guarantee the correct logic and the correct calling sequence. Most of the time, we need more than thread safety, but locks.

Finally, why is there a stringbuffer? If it is really worthless, why does jdk provide this class? The answer is too simple, because at first there was no stringbuilder, people at sun did not know what kind of stupid consideration, decided to make stringbuffer thread-safe, and then about 10 years later, people finally realized how stupid this decision was, conscious In the past 10 years, this stupid decision has contributed much power to the rumor that Java is running slowly. So, when jdk1.5 was finally decided to provide a non-thread-safe stringbuffer implementation, and named it stringbuilder. By the way, javac seems to have started from this version, all string operations connected with plus signs are implicitly rewritten into stringbuilder, that is to say, starting from jdk1.5, there is no performance loss in splicing strings with plus signs. .

If there is no loop , there is no performance loss for splicing strings with a plus sign in a single line , because the java compiler will implicitly replace it with stringbuilder.
However, in the case of loops , the compiler cannot achieve a smart enough replacement, and there will be performance loss .
Therefore, when splicing strings with loops, use stringbuilder honestly.

68 original articles have been published · 128 praised · 80,000 views

Guess you like

Origin blog.csdn.net/qq_39380155/article/details/105536476