Java Reference
In-Depth Information
public class StringComparison {
public static void main(String[] args) {
String str1 = new String("one");
String str2 = new String("one");
str1 = str1.intern();
str2 = str2.intern();
System.out.println(str1 == str2); // Prints "true"
}
}
Use of String.intern() should be reserved for cases in which the tokenization of
strings either yields an important performance enhancement or dramatically simplifies
code. Examples include programs engaged in natural language processing and compiler-
like tools that tokenize program input. For most other programs, performance and readab-
ility are often improved by the use of code that applies the Object.equals() approach
and that lacks any dependence on reference equality.
The JLS provides few guarantees about the implementation of String.intern() . For
example,
The cost of String.intern() grows as the number of intern strings grows. Per-
formance should be no worse than O( n log n ), but the JLS lacks a specific per-
formance guarantee.
In early Java Virtual Machine (JVM) implementations, interned strings became
immortal: they were exempt from garbage collection. This can be problematic
when large numbers of strings are interned. More recent implementations can
garbage-collect the storage occupied by interned strings that are no longer refer-
enced. However, the JLS lacks any specification of this behavior.
In JVM implementations prior to Java 1.7, interned strings are allocated in the
permgen storage region, which is typically much smaller than the rest of the heap.
Consequently, interning large numbers of strings can lead to an out-of-memory
condition. In many Java 1.7 implementations, interned strings are allocated on the
heap, relieving this restriction. Once again, the details of allocation are unspeci-
fied by the JLS ; consequently, implementations may vary.
Stringinterningmayalsobeusedinprogramsthatacceptrepetitivelyoccurringstrings.
Its use boosts the performance of comparisons and minimizes memory consumption.
Search WWH ::




Custom Search