LoginSignup
7
2

More than 5 years have passed since last update.

List#toArray の 引数って size と0 どっちがはやいの?

Last updated at Posted at 2018-05-31

まず結論

  • toArray(new T[0]) の方がはやいっす。

経緯

  • list.toArray は size の方がパフォーマンスがいい!と覚えていた。
  • ちょっとググると、内部実装を踏まえ、そのように書いてあるページばかりだ。

  • しかし、VMのパフォーマンスも日々進化している。

  • 2018/05/31 現在において、本当にそうなのだろうか。

→ 実験してみよう!

前提

  • ランタイムのバージョンや実行環境によって、後述の限りではないので、鵜呑みにしないで下さい。
  • 内部実装は見てません。

実験コード


import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(String[] args) {

        List<String> list = new ArrayList<>();
        for (int i = 0; i < 1000; i++) {
            list.add(Integer.toString(i));
        }

        int[] loopCounts = new int[] { 1000, 10000, 100000, 1000000, 10000000 };
        for (int loop : loopCounts) {
            long sum = 0;
            for (int j = 0; j < 10; j++) {
                long start = System.currentTimeMillis();

                String[] temp = null;
                for (int i = 0; i < loop; i++) {
                    temp = list.toArray(new String[0]);
                }

                long stop = System.currentTimeMillis();
                sum += stop - start;
            }
            System.out.println("toArray(new String[0]) " + loop + "回の速度*10回の平均速度は " + sum / 10 + " ミリ秒です。");

            sum = 0;
            for (int j = 0; j < 10; j++) {
                long start = System.currentTimeMillis();

                String[] temp = null;
                for (int i = 0; i < loop; i++) {
                    temp = list.toArray(new String[list.size()]);
                }

                long stop = System.currentTimeMillis();
                sum += stop - start;
            }
            System.out.println("toArray(new String[list.size()]) " + loop + "回の速度*10回の平均速度は " + sum / 10 + " ミリ秒です。");
        }
    }
}

結果

【1,000回】

toArray(new String[0]) 1000回の速度*10回の

平均速度は 2 ミリ秒です。

toArray(new String[list.size()]) 1000回の速度*10回の

平均速度は 2 ミリ秒です。

【10,000回】

toArray(new String[0]) 10000回の速度*10回の

平均速度は 19 ミリ秒です。

toArray(new String[list.size()]) 10000回の速度*10回の

平均速度は 25 ミリ秒です。

【100,000回】

toArray(new String[0]) 100000回の速度*10回の

平均速度は 207 ミリ秒です。

toArray(new String[list.size()]) 100000回の速度*10回の

平均速度は 288 ミリ秒です。

【1,000,000回】

toArray(new String[0]) 1000000回の速度*10回の

平均速度は 1497 ミリ秒です。

toArray(new String[list.size()]) 1000000回の速度*10回の

平均速度は 1562 ミリ秒です。

【10,000,000回】

toArray(new String[0]) 10000000回の速度*10回の

平均速度は 12949 ミリ秒です。

toArray(new String[list.size()]) 10000000回の速度*10回の

平均速度は 15622 ミリ秒です。

改めて結論

toArray(new T[0]) の方がはやい!

あとがき

ネットでググって出てきた記事に書いてあるから ってのはアカンなぁ(自戒)

参考になりそうなURL

外部リンク:Arrays of Wisdom of the Ancients

7
2
2

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
7
2