[英]Why is a binary search over a sorted vector is slower than std::set find?
Here you can see the code, run it and see the times. 在这里,您可以查看代码,运行代码并查看时间。
http://rextester.com/MNQZS47293 http://rextester.com/MNQZS47293
I get similar results on my machine (using the same version of MSVC), the lookup in the vector is slower than in the std::set. 在我的机器上(使用相同版本的MSVC),我得到了类似的结果,向量中的查找比std :: set中的查找慢。
I would expect the sorted vector version to be faster, due to better locality of the data (more cache friendly). 我希望排序后的矢量版本会更快,因为数据的位置更好(对缓存更友好)。 In the worse case, I would expect them to be similar, because they both perform a binary search, but I cannot understand why the std::set is much faster than the sorted vector version. 在最坏的情况下,我希望它们是相似的,因为它们都执行二进制搜索,但是我不明白为什么std :: set比排序的矢量版本快得多。
Thank you very much 非常感谢你
Edit: Sorry, I pasted the wrong link (I modified the code but forgot to copy the link) the old code was using an unordered_set, this code is using a set, and the question remains the same: Why is the binary search over a sorted vector slower than over a set? 编辑:对不起,我粘贴了错误的链接(我修改了代码,但忘记复制链接),旧代码使用的是unordered_set,此代码使用的是set,问题仍然相同:为什么对a进行二进制搜索排序向量比集合慢? I've noticed that if the number of elements is large enough, then the sorted vector is faster, but I still cannot understand why the set can outperform the sorted vector for any number of elements. 我注意到,如果元素的数量足够大,则排序后的向量会更快,但是我仍然无法理解为什么集合对于任何数量的元素都可以胜过排序后的向量。
The linked code seem to use unordered_set
, not set
. 链接的代码似乎使用unordered_set
而不是set
。
unordered_set
is a hash table. unordered_set
是一个哈希表。 There the search is not binary search. 那里的搜索不是二进制搜索。 There, search performance depends on the hash function and the load factor. 在那里,搜索性能取决于哈希函数和负载因子。
For the updated question: 对于更新的问题:
-O1
and -O2
gives the same performance for the two methods. -O1
和-O2
两种方法的性能相同。
-Ox
slows down the vector version. -Ox
减慢矢量版本。
Why this is, you need to look at the disassembly or at the details of the -Ox
level. 原因为何,您需要查看反汇编或-Ox
级别的详细信息。 It has nothing to do with the algorithmic properties of set.find
and lower_bound/binary_search
. 它与set.find
和lower_bound/binary_search
的算法属性lower_bound/binary_search
。
Regarding the locality of data. 关于数据的局部性。 A binary_search and a set::find has for reasonable implementations exactly the same locality of data. 对于合理的实现,binary_search和set :: find具有完全相同的数据位置。 The set might even win with the data being read in a left-to-right fashion. 该集合甚至可能以从左到右的方式读取数据而获胜。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.