问题描述
我试图通过 for 循环并使用 Collections 提供的 addAll() 方法将 2 个集合中的整数添加到单个 Set 中.出于测试目的,我用整数填充了 2 个集合,然后尝试将它们添加到第三个集合中
I was trying to add Integers from 2 sets into single Set via for loop and also using addAll() method provided by Collections. For test purpose, I have populated 2 Sets with Integers and then tried adding them to third set
Set<Integer> undId = new HashSet<Integer>();
Set<Integer> proxies = new HashSet<Integer>();
//Create 2 sets with Integers
for(int i=0;i<100;i++){
undId.add(i);
proxies.add(i);
}
和方法 1 ://现在使用 for 循环将它们添加到第三组
and method 1 : //Now add them to third set using for loop
for(Integer integer : undId)
underlyings.add(integer);
for(Integer integer :proxies)
underlyings.add(integer);
和方法 2 ://或者使用 addAll() 将它们添加到第三组
and method 2 ://Or add them to third set using addAll()
underlyings.addAll(undId);
underlyings.addAll(proxies);
现在,当我尝试使用 System.nanoTime() 为操作计时时,添加速度快了两倍(对于 100,1000,10000 个元素).当我将大小增加到 1000000 或 10000000 时,情况正好相反.我想知道为什么会发生更大的集合.我不确定 addAll() 内部如何处理,但对理解上述内容的任何帮助将不胜感激.谢谢
Now when i was trying to time the operation using System.nanoTime(), add is twice faster (for 100,1000,10000 elements). When i increased size to 1000000 or 10000000. It was reversed. I was wondering why would it happen for larger set. I am not sure how addAll() internally handles however any help in understanding above will be appreciated. Thnx
推荐答案
在你做任何事情之前,确保你已经阅读并理解了这里的讨论:Java 基准测试 - 为什么第二个循环更快?
Before you doing anything make sure you've read and understood the discussion here: Java benchmarking - why is the second loop faster?
我希望 addAll 在某些情况下会更快,因为它有更多的信息可供使用.
I would expect addAll to be faster in some situations as it has more information to work with.
例如,在 ArrayList 上 addAll 可以确保它分配足够的空间来一步添加每个元素,而如果添加大量元素,则不必多次重新分配.
For example on an ArrayList addAll can make sure it allocates enough space to add every single element in one step, rather than having to reallocate multiple times if adding large numbers of elements.
它当然不会变慢,因为即使是它的幼稚实现也会做你所做的,循环添加项目.
It would certainly not be slower as even a naive implementation of it would just do what you do, loop through adding the items.
这篇关于JAVA:设置 addAll() 与使用循环添加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!