java - 什么是 Java 字符串池以及 "s"与新字符串 ("s"有何不同?

标签 java string

字符串池是什么意思?以下声明之间有什么区别:

String s = "hello";
String s = new String("hello");

JVM对这两个字符串的存储有什么区别吗?

最佳答案

字符串池是 JVM 对 string interning 概念的特殊实现。 :

In computer science, string interning is a method of storing only one copy of each distinct string value, which must be immutable. Interning strings makes some string processing tasks more time- or space-efficient at the cost of requiring more time when the string is created or interned. The distinct values are stored in a string intern pool.

基本上,字符串实习池允许运行时通过在池中保存不可变字符串来节省内存,以便应用程序的区域可以重用公共(public)字符串的实例,而不是创建多个实例。

作为一个有趣的旁注,字符串实习是 flyweight design pattern 的一个示例。 :

Flyweight is a software design pattern. A flyweight is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory.

关于java - 什么是 Java 字符串池以及 "s"与新字符串 ("s"有何不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2486191/

相关文章:

java - Spring Data @NamedQuery 和 @NamedNativeQuery 有什么区别?

java - 使用 Aether 获取 MavenProject 的所有依赖项(包括传递性依赖项)

string - 在 R 中用 ' [ ] ' 拆分一个字符串向量

java - 如何在测试类中的 main 中 stub 函数(java)

java - adb shell 将当前所有目录复制到新文件夹

java - 无法从 URL 获取 JSONObject

java - 查找字符串中的各种字符

string - PowerShell字符串串联给出了换行符

php - 问号出现时 parse_str 不起作用?

java - 如何获取字符串中正则表达式的第一个匹配项?