灵感来自 this question 上的评论,我很确定 Java String
是在运行时而不是编译时驻留的——当然这只是类可以在不同时间编译的事实,但在运行时仍会指向相同的引用。
我似乎找不到任何证据来支持这一点。谁能证明这一点?
最佳答案
优化发生(或至少可以发生)在两个地方:
- 如果对同一字符串常量的两个引用出现在同一个类中,我希望类文件只包含一个常量池条目。为了确保在 JVM 中只创建一个
String
对象,这并不是严格必需的,但这是一项显而易见的优化。这实际上并不是实习 - 只是不断优化。 - 加载类时,将类的字符串池添加到实习生池中。这是“真正的”实习。
(我模糊地记得 Java 7 围绕“小 jar 文件”的一些工作包括为整个 jar 文件使用一个字符串池……但我可能错了。)
编辑:JVM 规范第 5.1 节,"The Runtime Constant Pool"详细介绍:
To derive a string literal, the Java virtual machine examines the sequence of characters given by the CONSTANT_String_info structure.
If the method String.intern has previously been called on an instance of class String containing a sequence of Unicode characters identical to that given by the CONSTANT_String_info structure, then the result of string literal derivation is a reference to that same instance of class String.
Otherwise, a new instance of class String is created containing the sequence of Unicode characters given by the CONSTANT_String_info structure; that class instance is the result of string literal derivation. Finally, the intern method of the new String instance is invoked.
关于java - Java 字符串什么时候被驻留?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3451145/