美团团队技术博客深入解析String#intern提到 intern 正确使用例子的代码如下
static final int MAX = 1000 * 10000;
static final String[] arr = new String[MAX];
public static void main(String[] args) throws Exception {
Integer[] DB_DATA = new Integer[10];
Random random = new Random(10 * 10000);
for (int i = 0; i < DB_DATA.length; i++) {
DB_DATA[i] = random.nextInt();
}
long t = System.currentTimeMillis();
for (int i = 0; i < MAX; i++) {
//arr[i] = new String(String.valueOf(DB_DATA[i % DB_DATA.length]));
arr[i] = new String(String.valueOf(DB_DATA[i % DB_DATA.length])).intern();
}
System.out.println((System.currentTimeMillis() - t) + "ms");
System.gc();
}
很好奇为什么要
arr[i] = new String(String.valueOf(DB_DATA[i % DB_DATA.length])).intern();
而不是直接
arr[i] = String.valueOf(DB_DATA[i % DB_DATA.length]);
而且String.intern() is meant to decrease memory use.
,这样子new String后再intern完全不能提升性能吧?
黄舟2017-04-17 16:16:23
The purpose of new String().intern() is to save memory space. After intern, if the literal value of the string is the same, then there is no need to waste space to create a new String object, and directly use the object in the constant pool Just quote it.
Of course, the step of new String() is inevitable (String.valueOf is ultimately new String internally), but there is no variable referencing this instance after new String (the return value of intern() referenced by arr[i], which is the constant pool object) will be recycled by GC soon.