话说最近重新温习Thinking in java(4th)。顺便说一下,真的是需要莫大的勇气读完这么厚一本书啊。
目前看到持有对象这一章,说Java中的集合类的。想想自己也用Java有2年多了,这些基础也应该会比较简单。刚看两行,被一句话吸引了"Collection.addAll()方法运行起来要快得多"。遂抱着求证的心态写了一些测试用例(代码丑陋,勿喷)。
public void utilMethodTest(){
//通过Arrays.asList方法初始化一个list,并将这个list作为ArrayList的构造参数,构造一个ArrayList
long a=System.nanoTime();
Collection<Integer> collection = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5));
System.out.println("\r<br>执行耗时 : "+(System.nanoTime()-a)+" 纳秒 ");
a=System.nanoTime();
Collection<Integer> c = new ArrayList<Integer>();
c.addAll(Arrays.asList(6,7,8,9,10));
System.out.println("\r<br>执行耗时 : "+(System.nanoTime()-a)+" 纳秒 ");
a=System.nanoTime();
Collection<Integer> c2 = new ArrayList<Integer>();
Collections.addAll(c2, 11,12,13,14,15);
System.out.println("\r<br>执行耗时 : "+(System.nanoTime()-a)+" 纳秒 ");
}
测试结果如下:
被测试方法 | 测试次数 | 执行时间(纳秒) | 平均值(纳秒) |
new Collection(Collection colection) | 1 | 32080 | 35159.2 |
2 | 35501 | ||
3 | 42773 | ||
4 | 30796 | ||
5 | 34646 | ||
Collection.addAll() | 1 | 11121 | 11634.2 |
2 | 11121 | ||
3 | 14115 | ||
4 | 10693 | ||
5 | 11121 | ||
Collections.addAll() | 1 | 19248 | 19846.6 |
2 | 18392 | ||
3 | 22670 | ||
4 | 19248 | ||
5 | 19675 |
结果很直观,Collection.addAll()方法最快,而且执行时间上比较稳定。
所以,如果是创建一个已知序列的集合类示例,尽量通过Collection.addAll方法进行创建。
但是Collections.addAll方法参数更为灵活,而且创建速度也比较快。也不失为一个比较好的选择。