java - Java 字符串什么时候被驻留?

标签 java string

灵感来自 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/

相关文章:

Java广播: throw BindException

java - 使用正则表达式获取字符串的首字母,同时保留标点符号和空格

javascript - 如果 JavaScript 中的字符串是不可变的,为什么下面的代码会改变字符串?

C 将数据作为字符串读取并将其转换为 float 并写回文件中

java - 地雷周围的扫雷游戏 block

java - 内存泄漏: Thread objects not picked up by GC or is it a classloading issue?

java - 用JSP获取当前页面节点

string - strconv.ParseInt 给出 0

c# - 我怎样才能加快这个循环?是否有一次替换多个术语的类?

java - 如何在 Javadoc 中包含 Google Analytics 片段?