美团团队技术博客深入解析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完全不能提升性能吧?
new String().intern()의 목적은 메모리 공간을 절약하는 것입니다. 인턴 이후 문자열의 리터럴 값이 동일하면 새 String 객체를 생성하기 위해 공간을 낭비할 필요가 없습니다. 상수 풀에서 직접 사용하면 됩니다.
물론 new String() 단계는 불가피하지만(String.valueOf는 내부적으로 궁극적으로 new String임) new String(arr[i]에서 참조하는 intern()의 반환 값) 이후에 이 인스턴스를 참조하는 변수가 없습니다. 풀의 상수 개체)는 곧 GC에 의해 재활용됩니다.