How many objects will the above line of code create?
The string literal is represented at runtime by one String
object. If that object hasn't yet been created, it may be created (lazily) by the execution of this statement. In either case, the object representing the literal will have been interned. (The number of String
objects that are created in this process is an implementation detail that depends on the Java version. Yes, really.)
The new String(...)
creates an object each time you do it.
Since the original String
o bject was interned, the intern()
call will return that object; i.e. the String
that represents the string literal: the one you started with.
So, in summary, your code may lead to the creation of up to three objects, directly and behind the scenes, but the object created by the new
will be unreachable by the end of the statement.
Indeed, since,
String a = new String("abc").intern();
and
String a = "abc";
give identical results, the new
/ intern
sequence is complete waste of time.
If it will create an object in heap memory as well as string pool memory then how is the intern() method increasing performance?
It doesn't directly increase performance:
There is a potential indirect benefit if you can intern all of the strings in a data structure. Then you can use ==
rather than equals(Object)
to test for equality.
However, you are trading off the cost of equals
versus the cost if intern
, so you need to make a few object comparisons before you get a net performance win. In addition, if you forget to intern one of the strings, ==
is liable to give you a different answer to equals
. (That's probably a bug!)
In older JVMs, there is a potential indirect benefit if you have a lot of long-lived String
objects. Using intern
to de-dup will reduce long-term memory usage and reduce long-term GC costs.
However, in recent JVMs the GC will automatically de-dup String
objects that survive a few GC cycles. Since this only applies to relatively long-lived objects, this is a more efficient way to de-dup. And the process is transparent to the application!
In short, under most circumstances there are no advantages and significant disadvantages to using the intern()
method in application code. Leave it alone.