Real Life, Practical Example of Using String.intern() in Java?

后端 未结 5 1133
挽巷
挽巷 2021-01-01 11:47

I\'ve seen many primitive examples describing how String intern()\'ing works, but I have yet to see a real-life use-case that would benefit from it.

The only situati

5条回答
  •  盖世英雄少女心
    2021-01-01 12:18

    Examples where interning will be beneficial involve a large numbers strings where:

    • the strings are likely to survive multiple GC cycles, and
    • there are likely to be multiple copies of a large percentage of the Strings.

    Typical examples involve splitting / parsing a text into symbols (words, identifiers, URIs) and then attaching those symbols to long-lived data structures. XML processing, programming language compilation and RDF / OWL triple stores spring to mind as applications where interning is likely to be beneficial.

    But interning is not without its problems, especially if it turns out that the assumptions above are not correct:

    • the pool data structure used to hold the interned strings takes extra space,
    • interning takes time, and
    • interning doesn't prevent the creation of the duplicate string in the first place.

    Finally, interning potentially increases GC overheads by increasing the number of objects that need to be traced and copied, and by increasing the number of weak references that need to be dealt with. This increase in overheads has to be balanced against the decrease in GC overheads that results from effective interning.

提交回复
热议问题