The Magnificent JavaJava学习笔记程序员

Collections.addAll 和collection.a

2016-06-12  本文已影响282人  IT_Matters

o>from: http://stackoverflow.com/a/3343829/5032462

在stackoverflow上看到的一篇回答,老外真是太professional了,mark一下,我稍微改了改,加了点自己的批注,最后的summary推荐大家看一下。

The Java API docs say the following about Collections.addAll

The behavior of this convenience method is identical to that of c.addAll(Arrays.asList(elements)), but this method is likely to run significantly faster under most implementations.

速度上来说,Collections.addAll要比collection.addAll更快,举例来说。

//a)
Collection<Integer> col = new ArrayList<Integer>();
col.addAll(Arrays.asList(1, 2, 3, 4, 5));

Here's what happens:

  1. varags + autoboxing creates Integer[]
  2. Arrays.asList creates a List<Integer> backed by the array
  3. addAll iterates over a Collection<Integer> using Iterator<Integer>
// b)
Collections.addAll(col, 1, 2, 3, 4, 5);

Here's what happens:

  1. varargs + autoboxing creates Integer[]
  2. addAll iterates over an array (instead of an Iterable<Integer>)

We can see now that b) may be faster because: Arrays.asList call is skipped, i.e. no intermediary List is created. Since the elements are given in an array (thanks to varargs mechanism), iterating over them may be faster than using Iterator.

__
That said, unless profiling shows otherwise, the difference isn't likely to be "significant". Do not optimize prematurely. While Java Collection Framework classes may be slower than arrays, they perform more than adequately for most applications.
__

API links


Collections.addAll(Collection<? super T> c,T... elements)
-varargs i.e. array-based
Collection.addAll(Collection<? extends E> c)
- Collection-based

See also


Java Language Guide/Autoboxing
Java Language Guide/Varargs
Effective Java 2nd Edition, Item 25: Prefer lists to arrays

Related questions
Array or List in Java. Which is faster ?


Summary

上一篇下一篇

猜你喜欢

热点阅读