字符串池是什么意思?以下声明之间有什么区别:
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/