Avoid duplicate Strings in Java

前端 未结 5 1092
独厮守ぢ
独厮守ぢ 2021-01-03 09:37

I want to ask a question about avoiding String duplicates in Java.

The context is: an XML with tags and attributes like this one:



        
5条回答
  •  离开以前
    2021-01-03 09:52

    Yes, interning is the correct solution and you'd done your homework (that is checking with profiler that this is the problem).

    Interning can cause problem if you store too much. The permgen memory needs to be increased. Despite what some people said, interned Strings are also garbage collected, so if some strings are not used anymore, it will be object to be garbage collected.

    Some supporting articles:

    1. My blog: http://blog.firdau.si/2009/01/06/java-tips-memory-optimization-for-string/
    2. Does intern garbage collected?: http://www.javaworld.com/javaworld/javaqa/2003-12/01-qa-1212-intern.html
    3. Busting the 'Busting String.intern() Myths': http://kohlerm.blogspot.com/2009/01/is-javalangstringintern-really-evil.html

提交回复
热议问题