<p>性能问题归结为<code>HashMap</code>和<code>HashSet</code>的默认哈希实现。Rust的默认哈希算法是一个很好的通用算法,它还可以防止某些类型的DOS攻击。但是,对于非常小或非常大的数据量,它并不能很好地工作。在</p>
<p>一些分析显示,<code>make_hash<i32, std::collections::hash::map::RandomState></code>占用了整个运行时的41%。从<a href="http://blog.rust-lang.org/2016/03/02/Rust-1.7.html" rel="noreferrer">Rust 1.7</a>开始,您可以选择使用哪种哈希算法。切换到<a href="https://crates.io/crates/fnv" rel="noreferrer">FNV hashing algorithm</a>可以大大加快程序的速度:</p>
<pre><code>extern crate fnv;
use std::collections::HashSet;
use std::hash::BuildHasherDefault;
use fnv::FnvHasher;
fn main() {
let mut len_sums = 0;
for _ in 0..100000 {
let set_1: HashSet<i32, BuildHasherDefault<FnvHasher>> = (0..1000).collect();
let set_2: HashSet<i32, BuildHasherDefault<FnvHasher>> = (500..1500).collect();
let intersection_len = set_1.intersection(&set_2).count();
len_sums += intersection_len;
}
println!("{}", len_sums);
}
</code></pre>
<p>在我的机器上,这需要2.714s,而Python是9.203s</p>
<p>如果使用相同的<a href="https://stackoverflow.com/a/35440350/155423">changes to move the set building out of the loop</a>,Rust代码需要0.829秒,而Python代码是3.093秒</p>