LoginSignup
2
2

More than 3 years have passed since last update.

【Java】 ArrayList→配列変換ではサイズを指定するべきなのか

Last updated at Posted at 2020-04-29

配列のサイズを指定する場合

ListToArray.java
ArrayList<String> arrayList = new ArrayList<String>();
for(int i=0; i < 10000000;i++) { // ← 1億
    arrayList.add("A");
}
long array1Start = System.currentTimeMillis();
arrayList.toArray(new String[arrayList.size()]);              // ←←ここ
long array1End = System.currentTimeMillis();
System.out.println("処理時間:" + (array1End - array1Start) + " ms");

結果

処理時間:3179 ms

配列のサイズを指定しない場合

ListToArray.java
ArrayList<String> arrayList = new ArrayList<String>();
for(int i=0; i < 100000000;i++) { // ← 1億
    arrayList.add("A");
}
long array2Start = System.currentTimeMillis();
arrayList.toArray(new String[0]);              // ←←ここ
long array2End = System.currentTimeMillis();
System.out.println("処理時間:" + (array2End - array2Start) + " ms");

結果

処理時間:3047 ms

え、ほぼ同じ・・・
その時のマシンの状況によるが、ほぼ同じ結果になる

評価する

パフォーマンス

 処理時間はほぼ同じ
 参照元をコピーするだけだからか。

可読性

arrayList.toArray(new String[arrayList.size()]); //明示的でわかりやすい
arrayList.toArray(new String[0]);                //0の意味を考えてしまう

結論

パフォーマンスはほぼ変わらないが、
可読性の観点でサイズを指定するべき

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