Performance Implications of intern()
You'll learn why calling intern() on every string can hurt performance more than help, and when it's actually worth the cost.
The Hidden Cost
When you call intern() on a string, Java must perform a hash table lookup in the intern pool to check if that exact string already exists. If it doesn't, Java adds it to the pool. This operation involves:
- Computing the string's hash code
- Searching the hash table
- Potentially resizing the pool if it's getting full
- Synchronization overhead (the pool is shared across threads)
Each of these steps takes time. For a single call, it's negligible. But if you're calling intern() on thousands or millions of strings in a loop, you've turned a simple operation into a bottleneck.
When intern() Backfires
Antipattern:
for (String line : millionsOfLines) {
String processed = line.trim().intern(); // DON'T do this!
// ... use processed
}
Here, you're forcing every trimmed line through the hash table. If most lines are unique, you're paying the lookup cost plus storing them all in memory, negating any benefit.
When intern() Makes Sense
Use intern() judiciously when:
- You have many duplicate strings (like status codes: "SUCCESS", "FAILED")
- You can verify the duplicates actually exist in your data
- Memory savings outweigh the lookup overhead
- The strings are long-lived (interned strings stick around)
Think of it like a library card catalog: Looking up whether a book exists takes effort. If you rarely have duplicates, you're wasting time checking. But if you process the same book titles repeatedly, the catalog becomes efficient.
Key Takeaway:
intern() involves hash table lookups and synchronization overhead—use it only when you have proven duplicate strings and the memory savings justify the performance cost.