Why is string.intern() so slow?

前端 未结 4 893
萌比男神i
萌比男神i 2020-12-13 00:50

Before anyone questions the fact of using string.intern() at all, let me say that I need it in my particular application for memory and performance reasons.

4条回答
  •  攒了一身酷
    2020-12-13 01:14

    I can't speak from any great experience with it, but from the String docs:

    "When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the {@link #equals(Object)} method, then the string from the pool returned. Otherwise, this String object is added to the pool and a reference to this String object is returned."

    When dealing with large numbers of objects, any solution involving hashing will outperform one that doesn't. I think you're just seeing the result of misusing a Java language feature. Interning isn't there to act as a Map of strings for your use. You should use a Map for that (or Set, as appropriate). The String table is for optimization at the language level, not the app level.

提交回复
热议问题