[英]Is iterating through a TreeSet slower than iterating through a HashSet in Java?
I'm running some benchmarks. 我正在运行一些基准测试。 One of my tests depends on order, so I'm using a TreeSet for that.
我的一个测试取决于顺序,所以我正在使用TreeSet。 My second test doesn't, so I'm using a HashSet for it.
我的第二个测试没有,所以我正在使用HashSet。
I know that insertion is slower for the TreeSet. 我知道TreeSet的插入速度较慢。 But what about iterating through all elements?
但是如何迭代所有元素呢?
From a similar post ( Hashset vs Treeset ): 从类似的帖子( Hashset vs Treeset ):
HashSet is much faster than TreeSet (constant-time versus log-time for most operations like add, remove and contains) but offers no ordering guarantees like TreeSet. HashSet比TreeSet快得多(对于大多数操作,例如add,remove和contains,常量时间与日志时间相比),但不提供像TreeSet这样的排序保证。
first()
, last()
, headSet()
, and tailSet()
etc first()
, last()
, headSet()
和tailSet()
等 HashSet
and TreeSet
. HashSet
和TreeSet
之间。 Implemented as a hash table with a linked list running through it, however it provides insertion-ordered iteration which is not same as sorted traversal guaranteed by TreeSet . So choice of usage depends entirely on your needs but I feel that even if you need an ordered collection then you should still prefer HashSet to create the Set and then convert it into TreeSet. 因此,使用的选择完全取决于您的需求,但我觉得即使您需要有序集合,您仍然应该更喜欢HashSet来创建Set,然后将其转换为TreeSet。
Set<String> s = new TreeSet<String>(hashSet);
Set<String> s = new TreeSet<String>(hashSet);
TreeSets
internally uses TreeMaps
which are Red Black Trees
(special type of BST
) . TreeSets
内部使用TreeMaps
,它是Red Black Trees
(特殊类型的BST
)。
BST
Inorder Traversal is O(n)
BST
Inorder Traversal是O(n)
HashSets
internally uses HashMaps
which use an array
for holding Entry objects. HashSets
内部使用HashMaps
,它使用array
来保存Entry对象。
Here also traversal should be O(n)
. 这里的遍历也应该是
O(n)
。
Unless you write a benchmark it is going to be difficult to prove which is faster. 除非你写一个基准测试,否则很难证明哪个更快。
If you want stable ordering with (nearly) the performance of a HashSet
, then use a LinkedHashSet
. 如果你想要(几乎)
HashSet
的性能稳定排序,那么使用LinkedHashSet
。 You will still get constant-time operations, whereas I would assume a TreeSet
will get you logarithmic time. 你仍然会得到恒定时间的操作,而我认为
TreeSet
会让你获得对数时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.