der*_*oni 36 java collections performance
在Java的API文档说有关以下Collections.addAll
这种方便方法的行为与c.addAll(Arrays.asList(elements))的行为相同,但在大多数实现中,此方法可能运行得更快.
所以,如果我理解正确,a)比b)慢:
一个)
Collection<Integer> col = new ArrayList<Integer>();
col.addAll(Arrays.asList(1, 2, 3, 4, 5));
Run Code Online (Sandbox Code Playgroud)
b)
Collection<Integer> col = new ArrayList<Integer>();
// Collections.addAll(col, Arrays.asList(1, 2, 3, 4, 5)); <-- won't compile
Collections.addAll(col, 1, 2, 3, 4, 5);
Run Code Online (Sandbox Code Playgroud)
任何人都可以向我解释,为什么会这样?
编辑:更正的代码示例.thx到polygenelubricants
pol*_*nts 49
让我们仔细看看其中两个:
Run Code Online (Sandbox Code Playgroud)// a) col.addAll(Arrays.asList(1, 2, 3, 4, 5));
这是发生的事情:
Integer[]
Arrays.asList
创建一个List<Integer>
由数组支持addAll
迭代Collection<Integer>
使用Iterator<Integer>
Run Code Online (Sandbox Code Playgroud)// b) Collections.addAll(col, 1, 2, 3, 4, 5);
这是发生的事情:
Integer[]
addAll
迭代一个数组(而不是一个Iterable<Integer>
)我们现在可以看到b)
可能更快,因为:
Arrays.asList
跳过调用,即没有List
创建中介.Iterator
.也就是说,除非剖析显示其他情况,否则差异可能不大"重要".不要过早优化.虽然Java Collection Framework类可能比数组慢,但它们对大多数应用程序的执行效果都不错.
Collections.addAll(Collection<? super T> c, T... elements)
- varargs即基于数组Collection.addAll(Collection<? extends E> c)
- Collection
基于Collections.addAll(col, arr)
Collection
,请使用col.addAll(otherCol)
Collections.addAll(col, otherCol.toArray())
归档时间: |
|
查看次数: |
24533 次 |
最近记录: |