A, the difference between
1. Variable and immutable
The String class uses character arrays to hold strings, as shown in the following example. Because of the “final” modifier, we know that strings are immutable. Even if you call the concat method of String, you concatenate the String and recreate an object, assigning the value of the concatenated String to the newly created object.
private final char value[];
AbstractStringBuilder and StringBuffer both inherit from the AbstractStringBuilder class, and their internal implementation depends on the parent class. The char array defined in the parent class is a normal private variable that can be appended by append. AbstractStringBuilder implements the Appendable interface.
char[] value;
1.1. Why is String made immutable
The e design of strings to be immutable in Java is the result of a combination of considerations, including memory, synchronization, data structures, and security. In the following, I will summarize the reasons for this.
-
The String constant pool (String Pool, String Intern Pool, String Retention pool) is a special storage area in the Java heap memory. When a String object is created, the String value already exists in the constant pool. Instead of creating a new object, you reference an existing object.
As shown in the following code, only one actual String is created in the heap memory.
String s1 = "helloworld";
String s2 = "helloworld";
Copy the code
The schematic diagram is as follows:
If a string object is allowed to change, this can lead to all kinds of logical errors, such as changing one object affecting another independent object. Strictly speaking, this constant pool idea is an optimization.
- HashCode allows String objects to be cached HashCode Java’s HashCode for String objects is used frequently, such as in containers such as hashMap. String invariance ensures that hash codes are unique and therefore can be safely cached. This is also a performance optimization, meaning you don’t have to compute a new hash code every time.
- Security Strings are used as arguments by many Java classes (libraries). For example, network connection address URL, file path, and String parameters required by reflection mechanism. If String is not fixed, all kinds of security risks arise.
1.2. Benefits of String class immutability
- String pooling is only possible if strings are immutable. The implementation of a string pool can save a lot of heap space at run time because different string variables point to the same string in the pool. But if strings are mutable, String interning will not be implemented. Because then, if a variable changes its value, the values of other variables that refer to that value change too.
- If the string is mutable, this can cause serious security problems. For example, the database user name and password are passed as strings to get a connection to the database, or in socket programming, the host name and port are passed as strings. Because a string is immutable, its value is immutable, or hackers can exploit a loophole by changing the value of the object to which the string points.
- Because strings are immutable, they are multithread safe, and the same string instance can be shared by multiple threads. This eliminates the need to use synchronization for thread-safety reasons. Strings themselves are thread-safe.
- Class loaders use strings, and immutability provides security so that the correct class is loaded. For example, if you want to load the java.sql.Connection class, and the value is changed to myhacked.Connection, you will do some unknown damage to your database.
- Because the string is immutable, hashCode is cached when it is created and does not need to be recalculated. This makes strings suitable as keys in maps, and strings are processed faster than other key objects. This is why keys in a HashMap tend to use strings.
2. Execution efficiency
StringBuilder > StringBuffer > String
String is the slowest.
String is a String constant, while StringBuilder and StringBuffer are String variables, meaning that a String object cannot be changed once created, whereas the latter two objects are variables and can be changed. Take the following code for example:
String str="abc";
System.out.println(str);
str=str+"de";
System.out.println(str);
Copy the code
If you run this code, you’ll see that it prints “ABC” and then “abcde” as if STR has been changed. This is just an illusion. The JVM does this by creating a String STR and assigning “ABC” to STR. In fact, the JVM creates a new object named STR, and then adds the value of the original STR and “de” to the new STR. The original STR is collected by the JVM’s garbage collection (GC), so STR is not actually changed. Once a String is created, it cannot be changed. So, Java operations on strings are really a process of constantly creating new objects and reclaiming old ones, so execution is slow.
StringBuilder and StringBuffer objects are variables, and manipulating variables directly changes the object without creating or recycling it, so it’s much faster than String.
Alternatively, we sometimes assign strings like this:
String str="abc"+"de";
StringBuilder stringBuilder=new StringBuilder().append("abc").append("de");
System.out.println(str);
System.out.println(stringBuilder.toString());
Copy the code
The output is also “abcde” and “abcde”, but String responds much faster than StringBuilder because the operation in line 1 and String STR = “abcde”;
It’s exactly the same, so it’s going to be fast, and if I write it like this:
String str1="abc";
String str2="de";
String str=str1+str2;
Copy the code
The JVM is constantly creating and recycling objects to do this, as described above. It’s going to be slow.
3, whether multi-threaded security
- Objects in strings are immutable, which means they can be interpreted as constants, which is obviously thread-safe.
- 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.
If the operation is multithreaded, use StringBuffer, but in single-threaded cases, the faster StringBuilder is recommended.
Second, the summary
String: Applies to a small number of String operations
StringBuilder: This is suitable for large operations in the character buffer under a single thread
StringBuffer: Applies to multiple threads where a large number of operations are performed in the character buffer