Why is there an intern method in java?

Possible duplicate:
When to use intern ()
When should we use the intern method for String?

Is java intern strings automatic? If so, why does the string have an explicit intern method? Any specific use cases where an explicit call is required?

+4
source share
3 answers

Java does not create internal strings created at runtime automatically. (He does this for string constants at compile time).

I had a specific use case when I saved ~ 30% of the heap used in the component that received the records expressed on the map. The set of keys in each record was identical, but each new record received created new instances of key strings. By interpolating the key strings, heap consumption has been significantly reduced.

+1
source

From JavaDoc: "All literals and string constant expressions are interned."

Runtime interpretation provides no performance benefits to my knowledge. It can protect you from heap if you have a lot of dynamically created string containing duplicates. For example, using your own hash for this seems safer to me.

0
source

It only puts string literals automatically. If you create a string yourself (from an input stream from a network, for example), it will not be interned. If you expect that there will be many instances of the same row, it might be worthwhile to intern them, instead of having many equivalent rows on the heap. Personally, I have never used it.

0
source

Source: https://habr.com/ru/post/1410856/


All Articles