Fundamentals 5 min read

The Dangers of Using String.intern() in Java: Debunking Common Myths

This article explains why using Java's String.intern() can be hazardous by disproving three popular myths about its performance benefits, memory savings, and lifetime, and offers guidance on when (if ever) the method should be applied.

Qunar Tech Salon
Qunar Tech Salon
Qunar Tech Salon
The Dangers of Using String.intern() in Java: Debunking Common Myths

Update: The discussion focuses on Java 6 where interned strings reside in the PermGen area; in Java 7 they moved to the heap, so the memory‑saving claim of intern() is no longer valid, though it still avoids creating duplicate objects on the heap.

Myth 1 – Using == is faster than equals(): Benchmarks show that == is only about five times faster than equals() for typical strings, and string comparison usually accounts for a tiny fraction of total execution time, so the overall performance gain is negligible.

Myth 2 – String.intern() saves a lot of heap memory: Interning actually moves strings from the heap to the limited PermGen space, which can quickly exhaust that area and cause OutOfMemoryError, as demonstrated by a simple test program that shows PermGen growth.

Myth 3 – Interned strings stay in memory forever: Modern JVMs garbage‑collect unreferenced interned strings, so they are released when no longer used, contrary to the belief that they persist until JVM shutdown.

When == can be useful: In extremely heavy text‑processing scenarios you might consider interning, but a better alternative is a WeakHashMap‑based string pool that provides uniqueness without consuming precious PermGen space.

Conclusion: If you do not fully understand the implications, using String.intern() is risky; knowing its drawbacks lets you make an informed decision.

JavaJVMperformancememory managementString.intern
Qunar Tech Salon
Written by

Qunar Tech Salon

Qunar Tech Salon is a learning and exchange platform for Qunar engineers and industry peers. We share cutting-edge technology trends and topics, providing a free platform for mid-to-senior technical professionals to exchange and learn.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.