什么是 string interning Link to heading
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.
— from Wikipedia
它在其中提到了 string intern pool, 那什么是 string intern pool 呢?
想象一个大池子, 里面只能放不同的 string, 如果你有两个不同的 string object s1 和 s2, 他们内容都是"abc", 那么当创建完 s1之后, java 自动会在 string intern pool中注册, 那么当第二次看到你又创建一个s2是相同的内容的时候, java 自动把 string intern pool 中的那个 reference 拿给你.(大致上是这样, 细节有不同, 往下看)
为什么用 string interning 呢? Link to heading
string interning 真的可以减少 object 的创建, 让程序变得 efficient. 同时, 如果 string 被 intern 了, 那么两个 string 可以用 ‘==’ 来比较, 可以不用equals()来比较.
什么时候会用到 string interning 呢? Link to heading
- 当用 constant 的方法创建 string, 比如
String s1 = "abc", 那么, java 自动为你intern() - 如果你用
new String()的方法创建, 那你必须显性调用intern()
给个例子 Link to heading
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1 = "abc";
String s2 = "abc";
String s3 = new String("abc");
System.out.println("test string");
System.out.println(s1==s2); // true
System.out.println(s1 == s3);//false
System.out.println(s2 == s3);//false
System.out.println("===============================");
System.out.println("test string creation interning");
s3 = s3.intern();
System.out.println(s1 == s3); // true
System.out.println(s2 == s3); // true
}
}
python 中的 string intern Link to heading
- python 中用 constant 创建字符串, python 自动会 intern()
- 只包含下划线、数字、字母的字符串才会被intern (python-like string)
- intern 以及 intern pool 只有在 compile time 的时候才会被操作. 如果在 runtime 对 string 有更改, string 不会自动被 intern, 即使 string 看起来是一样的.
关于数字常量池(integer pool) Link to heading
数字从-128127(还是0127 忘了)java 认为比较常用, 所以当用 constant 的方法创建 Integer 时候, java 会自动把这个 object 注册到常量池.
credit to