basyura's blog

あしたになったらほんきだす。

配列をがっちゃんこ

List でゴリっとつなげるか、System.arraycopy でゴリっとつなげるか。

import java.util.*;
public class ArraysTest {
	public static void main(String args[]) {

		int count = 10000;
		List l1 = new ArrayList();
		List l2 = new ArrayList();
		for(int i = 0 ; i < 100 ; i ++) {
			l1.add(Integer.toString(i));
			l2.add(Integer.toString(i+100));
		}
		String[] array1 = (String[])l1.toArray(new String[0]);
		String[] array2 = (String[])l2.toArray(new String[0]);
		
		Date st = new Date();

		for(int i = 0 ; i < count ; i++) {
			List list = new ArrayList();
			list.addAll(Arrays.asList(array1));
			list.addAll(Arrays.asList(array2));
		}

		System.out.println(new Date().getTime() - st.getTime());
		
		st = new Date();
		for(int i = 0 ; i < count ; i++) {
			String[] dest = new String[array1.length + array2.length];
			System.arraycopy(array1 , 0 , dest , 0 , array1.length);
			System.arraycopy(array2 , 0 , dest , array1.length ,  array2.length);
		}
		System.out.println(new Date().getTime() - st.getTime());
	}
}

94 [ms] と 18 [ms] 。System.arraycopy を使った方が 5 倍早いけど、平均したら誤差の範囲。がっちゃんこしようとする配列が 100 個ってのは経験的にはあまりないし。記述量的にも事故の少なそうな前者の方がいい気がする。共通処理とか何回も通るような所は別だけど。

jdk1.4 止まりがバレバレなソース。むやみやたらとジェネリクスを定義しまくるよりはいいと思うんだけど、きっと慣れの違い。