String.intern()
method. But not everyone uses it in their applications, or represents in which cases it is useful and useful at all. So it was with me until I encountered this method in one of the projects. At that moment I wanted to learn the meaning and features of its use and came across one very interesting article by the lead developer of Yahoo! by the name of Ethan Nicholas, the translation of which I now want to share with the part of the Habra community that is not indifferent to the Java language.protected final static String fVersionSymbol = "version".intern();
intern()
? Well, as you undoubtedly know, there are two different ways to compare objects in Java. You can use the ==
operator, or you can use the equals()
method. The ==
operator compares whether two references refer to the same object, while equals()
compares whether two objects contain the same data.equals()
rather than ==
to compare two strings. If we compare, say, new String("Hello") == new String("Hello")
, then the result will be false
, because these are two different instances of the class. If you use equals()
, then you get true
, as expected. Unfortunately, equals()
can be quite slow, since it performs character-by-character string comparisons.==
operator checks for identity (identity), all it has to do is compare two pointers, and obviously it will be much faster than equals()
. So if you are going to compare the same strings multiple times, you can get a significant performance advantage by using the identity check of objects instead of comparing characters.==
instead of equals()
, while gaining significant performance advantages in repeated comparisons.intern()
method in the java.lang.String
class. The expression new String("Hello").intern() == new String("Hello").intern()
returns true
, while without using intern()
returns false
.protected final static String fVersionSymbol = "version".intern();
"version"
), and other lines that are part of the class file format — class names, method signatures, and so on. This even applies to the expressions: "Hel" + "lo"
processed by javac
in the same way as "Hello"
, therefore "Hel" + "lo" == "Hello"
returns true
.intern()
for a constant string of type "version"
, by definition, will be exactly the same object that you declared. In other words, "version" == "version".intern()
always true. You need to intern strings when they are not constants, and you want to be able to quickly compare them with other interned strings.java.lang.Object
. The class name java.lang.Object
should appear in each of these classes, but, thanks to the magic of intern()
, it appears in memory only in one instance.intern()
is a useful method and can make life easier - but make sure you use it properly.Source: https://habr.com/ru/post/79913/
All Articles