在源代码中 com.sun.org.apache.xerces.internal.impl.XMLScanner在第 183 和 186 行
183 protected final static String fVersionSymbol = "version".intern();
186 protected final static String fEncodingSymbol = "encoding".intern();
为什么 "version" 和 "encoding" 是字符串文字并且会自动被 intern 时使用 intern() 显式 intern?
最佳答案
我已经追踪到 revision 318617 in the Apache Xerces SVN Repository 的变化(正如包名所示,这是最初开发此 XML 解析器的项目)。
提交消息的相关部分是:
Trying to improve the use of symbol tables. Many predefined Strings are added to symbol tables every time the parser is reset. For small documents, this would be a significant cost. Now since we call String#intern for Strings in the symbol table, it's sufficient to use String#intern for those predefined symbols. This only needs to be performed once.
正如您所指出的,.intern()
对符合标准的 JVM 实现来说不是必需的(并且应该没有明显的影响)。
我的猜测是
- 或者作者没有意识到字符串文字将始终被保留
- 或者这是一个有意识的决定,以防止行为不当的 JVM 实现
但是,在第二种情况下,我希望在评论或评论消息中对此有所说明。
.intern()
调用的一个副作用是初始化器不再是 constant expressions并且字段不会被引用它们的其他类内联。这将确保加载类 XMLScanner
并读取其字段。不过,我认为这与此无关。
关于java - 字符串文字的自动驻留,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13196886/