0
0

javaのString.Intern()メソッドとパフォーマンス

Last updated at Posted at 2023-11-25

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
image.png
image.png
image.png
サンプルコード(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
image.png
image.png
image.png
ですので、intern()メソッドを使用すると、プールにあるものを使って、メモリ領域の節約ができって、GC回数を減らして、パフォーマンス向上ができました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0