gpt4 book ai didi

java - CopyOnWriteArraySet 太慢

转载 作者:行者123 更新时间:2023-11-29 06:52:09 25 4
gpt4 key购买 nike

当我运行以下程序时,执行大约需要 7 到 8 分钟。我真的不确定我哪里弄错了,因为这个程序执行起来要花很多时间。

public class Test {
public static void main(String[] args) {
final Integer[] a= new Integer[1000000];
for (int i=0; i < a.length; i++) {
a[i] = i;
}
final List<Integer> source = Arrays.asList(a);
final Set<Integer> set = new CopyOnWriteArraySet<Integer>(source);
}
}

谁能帮我理解,为什么这个程序太慢了。

我的机器是 Core I7 和 4GB 内存

最佳答案

我已经测试过,确实有一个包含 1 000 000 个元素的列表提供给构造函数,这需要很长时间(7 分钟)。

这是 Open JDK 2013-01-09 上的一个引用问题:
JDK-8005953 - CopyOnWriteArraySet copy constructor is unusable for large collections

此问题是由 CopyOnWriteArraySet 构造函数调用的 CopyOnWriteArrayList#addAllAbsent() 方法引起的。

问题摘录:

CopyOnWriteArraySet's copy constructor is too slow for large collections. It takes over 10 minutes on a developer laptop with just 1 million entries in the collection to be copied...

作为解决状态,您可以阅读:Won't Fix
您可以阅读最后一条消息:

addAllAbsent can be made faster for larger input, but it would impact the performance for small sizes. And it's documented that CopyOnWriteXXX classes are better suited for collections of small sizes.

CopyOnWriteArraySet javadoc确实指定了这一点:

It is best suited for applications in which set sizes generally stay small, read-only operations vastly outnumber mutative operations, and you need to prevent interference among threads during traversal.

关于java - CopyOnWriteArraySet 太慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44345481/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com