0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Java]文字列結合の速度比較

Last updated at Posted at 2020-11-11

javaで文字列の結合を手軽に行うときは+を使うが、
StringBuilderappendメソッドで結合すればパフォーマンスが上がるらしい。

public class StringConcate{
    public static void main(String args[]){
        for(int i=0; i<5; i++){
            // n=[10,100,1000,10000,100000]
            int NumOfProcess = (int)Math.pow(10, i+1);
            System.out.println("* n="+NumOfProcess);

            plusString(NumOfProcess);
            builderString(NumOfProcess);
        }
    }

    /** "+"を用いて文字列の結合を行い速度を表示する
     * @param n 結合処理回数
     */
    public static void plusString(int n) {
        long stime = System.currentTimeMillis(); // 処理開始時刻

        String s = "abc" ;
        for(int i=0; i<n; i++){
            s = s+"java" ;
        }

        long etime = System.currentTimeMillis(); // 処理終了時刻
        System.out.println("plusString process-time : "+(etime-stime)+"[ms]");
    }

    /** StringBuilderのappendメソッドを用いて文字列の結合を行い速度を表示する
     * @param n 結合処理回数
     */
    public static void builderString(int n) {
        long stime = System.currentTimeMillis(); // 処理開始時刻

        StringBuilder s = new StringBuilder("abc") ; // StringBuilderインスタンス生成
        for(int i=0; i<n; i++){
            s = s.append("java") ;
        }

        long etime = System.currentTimeMillis(); // 処理終了時刻
        System.out.println("StringBuilder process-time : "+(etime-stime)+"[ms]");
    }
}

それぞれ2つのメソッドに対して
"java"という文字列の結合を10回~100万回繰り返してみた。

* n=10
plusString process-time : 0[ms]
StringBuilder process-time : 0[ms]
* n=100
plusString process-time : 0[ms]
StringBuilder process-time : 0[ms]
* n=1000
plusString process-time : 2[ms]
StringBuilder process-time : 0[ms]
* n=10000
plusString process-time : 67[ms]
StringBuilder process-time : 1[ms]
* n=100000
plusString process-time : 3336[ms]
StringBuilder process-time : 0[ms]
* n=1000000
plusString process-time : 778282[ms]
StringBuilder process-time : 12[ms]

歴然たる差。100万回の結合では+を使うと13分もかかってしまった。
普段は+で、大量の結合処理を行うときにはStringBuilderを使うのがよさそう?

version情報

$ java -version
java version "14.0.1" 2020-04-14
Java(TM) SE Runtime Environment (build 14.0.1+7)

参考

スッキリわかるJava入門-実践編 第2版

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?