This is the 22nd day of my participation in the August Wen Challenge.More challenges in August
This article is from chaoCode, chaoCode, chaoCode, chaoCode and chaoCode.
Violators, the author reserves the right to pursue.
preface
Today we’ll look at the differences between String and StringBuffer and StringBuilder
The difference between
1.String and StringBuffer and StringBuilder are both classes in the Java.lang package
- java.lang.String
- java.lang.StringBuffer
- java.lang.StrungBuilder
2.String and StringBuffer and StringBuilder are final classes and are not allowed to be inherited. The following are explained in terms of variability, thread safety, and performance.
variability
To put it simply:
-
The String class uses final keyword arrays to hold strings. Private final char Value [], so strings are immutable.
-
AbstractStringBuilder and StringBuffer both inherit from AbstractStringBuilder classes, AbstractStringBuilder also uses character arrays to hold the string char[]value without the final keyword, so both objects are mutable.
Thread safety
- Objects in strings are immutable, which means they are considered constants, thread-safe.
AbstractStringBuilder AbstractStringBuilder is a common parent of StringBuilder and StringBuffer. AbstractStringBuilder defines some basic string operations, such as expandCapacity, Append, insert, indexOf and other public methods.
-
StringBuffer places synchronization locks on methods or on invoked methods, so it is thread-safe.
-
StringBuilder does not lock methods synchronously-so it is not thread-safe.
performance
-
Each time a String type is changed, a new String is generated and a pointer is pointed to the new String.
-
A StringBuffer operates on the StringBuffer object itself each time, rather than generating new objects and changing object references.
-
Using StirngBuilder in the same situation yields only a 10% to 15% improvement over using StringBuffer, but at the risk of multithreading insecurity.
A summary of the three uses
- Operate on a small amount of data = String
- Single thread manipulation of large amounts of data in string buffer = StringBuilder
- Multithreaded manipulation of large amounts of data in string buffers = StringBuffer
Thank you for watching, if there is a mistake in the article, welcome to the comment section to communicate. If this article has helped you, please like it at 👍.