There are two forms of string object creation in Java, one in literal form, such as String str = "Droid", and the other is the method of using the standard constructed object of new, such as String str = new String ("Droid"); Both of these methods are often used when code is written, especially in the literal way. However, there are some differences in performance and memory usage between these two implementations. It all stems from the JVM in order to reduce the duplication of string objects, it maintains a special memory, which is either a string constant pool or a string literal pool.
Working principle
When you create a string object in literal form in code, the JVM first checks this literal and returns the reference if there is a reference to the string object of the same content in the string constant pool, otherwise the new string object is created, and then the reference is placed in a string constant pool and returned.
Give an example to explain
Literal creation Form
Copy Code code as follows:
The JVM detects this literal, and here we think there is no content for the Droid object to exist. The JVM cannot find a string object with a string constant pool that is not in existence, then creates the string object, then puts the reference of the object just created into the string constant pool and returns the reference to the variable str1.
If there's a piece of code next
Copy Code code as follows:
Similarly, the JVM still detects this literal, and the JVM finds that the contents are "Droid" string objects by looking for a constant pool of strings, and then returns a reference to the existing string object to the variable str2. Note that the new string object is not recreated here.
To verify whether STR1 and str2 point to the same object, we can pass this code
Copy Code code as follows:
System.out.println (str1 = = str2);
The result is true.
Using new to create
Copy Code code as follows:
String str3 = new String ("Droid");
When we use new to construct a string object, a new string object is created regardless of whether there is a reference to the object in the string constant pool that has the same content. So we use the following code to test
Copy Code code as follows:
String str3 = new String ("Droid");
System.out.println (str1 = = STR3);
The result, as we think, is false, indicating that the two variables point to a different object.
Intern
For a string object created above using new, you can use the Intern method if you want to add a reference to the object to a string constant pool.
After calling intern, first check that the string constant pool has a reference to the object, and if so, return the reference to the variable, otherwise the reference is added and returned to the variable.
Copy Code code as follows:
String STR4 = Str3.intern ();
System.out.println (STR4 = = str1);
The result of the output is true.
Difficult issues
Prerequisites?
The prerequisite for a string constant pool implementation is that the string object in Java is immutable, so that multiple variables can be safely guaranteed to share the same object. If a string object in Java is mutable, a reference operation changes the value of the object, and other variables are affected, which is obviously unreasonable.
Reference or Object
The most common issue is the time reference or object that is stored in a string constant pool. The string constant pool holds an object reference, not an object. In Java, objects are created in heap memory.
Update verification, I received a lot of comments are also discussed this issue, I have simply verified. Verify the Environment:
Copy Code code as follows:
22:18:54-androidyue~/videos$ Cat/etc/os-release
Name=fedora
Version= "(Beefy Miracle)"
Id=fedora
Version_id=17
Pretty_name= "Fedora (beefy Miracle)"
Ansi_color= "0;34"
Cpe_name= "Cpe:/o:fedoraproject:fedora:17"
22:19:04-androidyue~/videos$ java-version
Java Version "1.7.0_25"
OpenJDK Runtime Environment (FEDORA-2.3.12.1.FC17-X86_64)
OpenJDK 64-bit Server VM (build 23.7-b01, Mixed mode)
Verification idea: The following Java program reads a video file size 82M, intern operation in string form.
Copy Code code as follows:
22:01:17-androidyue~/videos$ LL-LH | grep why_to_learn.mp4
-rw-rw-r--. 1 Androidyue Androidyue 82M Oct 2013 Why_to_learn.mp4
Validating code
Copy Code code as follows:
Import Java.io.BufferedReader;
Import java.io.FileNotFoundException;
Import Java.io.FileReader;
Import java.io.IOException;
public class Testmain {
private static String filecontent;
public static void Main (string[] args) {
Filecontent = readfiletostring (Args[0]);
if (null!= filecontent) {
Filecontent = Filecontent.intern ();
System.out.println ("not Null");
}
}
private static string readfiletostring (string file) {
BufferedReader reader = null;
try {
reader = new BufferedReader (new FileReader (file));
StringBuffer buff = new StringBuffer ();
String Line;
while (line = Reader.readline ())!= null) {
Buff.append (line);
}
return buff.tostring ();
catch (FileNotFoundException e) {
E.printstacktrace ();
catch (IOException e) {
E.printstacktrace ();
finally {
if (null!= reader) {
try {
Reader.close ();
catch (IOException e) {
E.printstacktrace ();
}
}
}
return null;
}
}
Because the string constant pool exists in the heap memory for a permanent generation, it is applied before Java8. We validate by setting a permanent surrogate for a very small value. If a string object exists in a string constant pool, then the Java.lang.OutOfMemoryError PermGen space error must be thrown.
Copy Code code as follows:
java-xx:permsize=6m Testmain ~/videos/why_to_learn.mp4
Running the proof program does not throw oom, in fact this can not be a good proof of the stored object or reference.
But the actual content object char[], which at least proves the string, is not stored in a string constant pool. In this case, it is not so important that the string constant pool store the string object or the reference to the string object. But individuals still tend to be stored as references.
Disadvantages
The benefit of a string constant pool is to reduce the creation of the same content string and save memory space.
If you want to say the drawbacks, it is to sacrifice the CPU time to change space. CPU computing time is primarily used to find references to objects that have the same content in a string constant pool. But its internal implementation is Hashtable, so the computational cost is low.
GC Recycle?
Because the string constant pool holds a reference to the shared string object, does that mean that the objects cannot be recycled?
The objects shared in the first question are generally small. As far as I'm aware, this problem does exist in earlier versions, but with the introduction of weak references, this problem should not be present.
On this issue, you can specifically understand this article interned Strings:java Glossary
Intern use?
The premise of using intern is that you know you really need to use it. For example, we have a record of millions of records in the United States of California, we do not want to create a string object such as millions, we can use intern only in memory to keep a copy. For more in-depth understanding of intern, please refer to the in-depth analysis of String#intern.
There are always exceptions?
Do you know the following code that creates a few string objects that hold several references in a string constant pool?
Copy Code code as follows:
String test = "a" + "B" + "C";
The answer is to create only one object, and only one reference is saved in the constant pool. We can tell by using JAVAP decompile.
Copy Code code as follows:
17:02 $ javap-c TESTINTERNEDPOOLGC
Compiled from "Testinternedpoolgc.java"
public class TESTINTERNEDPOOLGC extends java.lang.object{
public TESTINTERNEDPOOLGC ();
Code:
0:aload_0
1:invokespecial #1; Method Java/lang/object. " <init> ":() V
4:return
public static void Main (java.lang.string[]) throws java.lang.Exception;
Code:
0:LDC #2; String ABC
2:astore_1
3:return
See, in fact, during compilation, these three literal quantities have been synthesized one. This is actually an optimization that avoids the creation of extra string objects and no string concatenation problems. For string concatenation, you can view Java details: concatenation of strings.