String.Intern()メソッド
文字列オブジェクトの正準表現を返します。
文字列のプールは、初期状態では空で、クラスStringによってプライベートに保持されます。
internメソッドが呼び出されたときに、equals(Object)メソッドによってこのStringオブジェクトに等しいと判定される文字列がプールにすでにあった場合は、プール内の該当する文字列が返されます。そうでない場合は、このStringオブジェクトがプールに追加され、このStringオブジェクトへの参照が返されます。
パフォーマンス影響
サンプルコード(intern()メソッド使用しない)
public class StringInternTest {
public static void main(String[] args) {
final int maxCount= 1000 * 10000;
String arr[] = new String[maxCount];
Integer data[] = new Integer[] {1,2,3,4,5,6,7,8,9,10};
long start = System.currentTimeMillis();
for (int i=0; i<maxCount; i++) {
arr[i] = new String(String.valueOf(data[i%data.length]));
// arr[i] = new String(String.valueOf(data[i%data.length])).intern();
}
long end = System.currentTimeMillis();
System.out.println("The execute time is:"+ (end-start));
try {
Thread.sleep(1000000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
結果
The execute time is:3085
javaVisualVM
サンプルコード(intern()メソッド使用する)
public class StringInternTest {
public static void main(String[] args) {
final int maxCount= 1000 * 10000;
String arr[] = new String[maxCount];
Integer data[] = new Integer[] {1,2,3,4,5,6,7,8,9,10};
long start = System.currentTimeMillis();
for (int i=0; i<maxCount; i++) {
// arr[i] = new String(String.valueOf(data[i%data.length]));
arr[i] = new String(String.valueOf(data[i%data.length])).intern();
}
long end = System.currentTimeMillis();
System.out.println("The execute time is:"+ (end-start));
try {
Thread.sleep(1000000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
結果
The execute time is:839
javaVisualVM
ですので、intern()メソッドを使用すると、プールにあるものを使って、メモリ領域の節約ができって、GC回数を減らして、パフォーマンス向上ができました。