简体   繁体   English

为什么LinkedHashSet上的迭代时间不取决于其容量?

[英]Why iteration time over a LinkedHashSet is not dependent on its capacity?

From the Java Docs of LinkedHashSet(LHS) class : LinkedHashSet(LHS)类的Java文档中

Iteration over a LinkedHashSet requires time proportional to the size of the set, regardless of its capacity. 在LinkedHashSet上进行迭代需要的时间与集合的大小成正比,而不管其容量如何。 Iteration over a HashSet is likely to be more expensive, requiring time proportional to its capacity. 在HashSet上进行迭代可能会更昂贵,需要的时间与其容量成正比。

My question is why does iteration time over a LHS has no bearing on the capacity of the set ? 我的问题是,为什么LHS上的迭代时间与集合的容量无关?

Because the LinkedHashSet comprises internally both a LinkedList and a Set. 因为LinkedHashSet内部包含一个LinkedList和一个Set。 When iterating, you iterate over the (I believe, double) LinkedList, not the HashSet. 迭代时,您遍历了(我相信是两倍)LinkedList,而不是HashSet。

创建一个容量为1MB的常规HashSet(新的HashSet(1024 * 1024),添加1个元素并尝试进行迭代。尽管HashSet只有1个元素,但迭代器将必须遍历基础hastable的所有1MB存储桶。它是一个LinkedHashSet,迭代器不会遍历哈希表(该哈希表仅用于get()和contains()),但会通过LinkedList(并行结构),并且其中只有一个元素。

Iterating over a HashSet you need (pretty much) iterate over the buckets that contain the elements, then to eliminate empty values, which requires additional time. 遍历HashSet时,您需要(几乎)遍历包含元素的存储桶,然后消除空值,这需要额外的时间。 Briefly - there is some overhead associated with sorting empty elements out. 简而言之-与整理空元素相关的一些开销。

The nature of Linked collections is so that every element points to the next one. 链接集合的性质是,每个元素都指向下一个。 So, you start with the first and without much problems pull the next, and so on - this way you easily iterate them all. 因此,您可以从第一个开始,而没有很多问题,再从下一个开始,依此类推-这样您就可以轻松地迭代所有这些。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM