Rust HashMap容量疑问解析(基于Rust by Practice练习)
Rust HashMap 容量相关问题解答
示例代码
use std::collections::HashMap; fn main() { let mut map: HashMap<i32, i32> = HashMap::with_capacity(100); map.insert(1, 2); map.insert(3, 4); // Indeed ,the capacity of HashMap is not 100, so we can't compare the equality here. assert!(map.capacity() >= 100); println!("Capacity #1: {}", map.capacity()); // Shrinks the capacity of the map with a lower limit. It will drop // down no lower than the supplied limit while maintaining the internal rules // and possibly leaving some space in accordance with the resize policy. map.shrink_to(50); assert!(map.capacity() >= 50); println!("Capacity #2: {}", map.capacity()); // Shrinks the capacity of the map as much as possible. It will drop // down as much as possible while maintaining the internal rules // and possibly leaving some space in accordance with the resize policy. map.shrink_to_fit(); assert!(map.capacity() >= 2); println!("Capacity #3: {}", map.capacity()); println!("Success!"); }
运行输出
Capacity #1: 112 Capacity #2: 56 Capacity #3: 3 Success!
疑问解答
1. 初始化指定容量100,插入2个元素后容量为112的原因
Rust的HashMap不会严格遵循传入的容量值,而是会选择大于等于指定值的最小符合内部实现规则的容量。这些规则是为了优化哈希冲突概率、内存分配效率和访问性能设计的——比如容量会被调整为预设的阈值(通常是质数或特定对齐数值),确保后续插入元素时无需立即扩容,同时维持哈希表的高效运作。因此初始化指定100后,实际容量会调整为112。
2. 调用shrink_to(50)后实际容量为56的原因
shrink_to(n)的作用是将容量缩小到不小于n的最小值,但这个最小值必须符合HashMap的内部规则。即使当前只有2个元素,它也不会直接缩到50,因为50不符合哈希表的容量调整要求(比如不是预设阈值、无法满足负载因子限制)。56是满足“不小于50”且符合内部规则的最小容量,因此最终调整为56。
3. 调用shrink_to_fit()后容量为3而非2的原因
shrink_to_fit()会将容量缩到尽可能小,但同样要遵循HashMap的内部结构要求:
- 哈希表的桶数量不能小于某个最小值,否则会导致哈希冲突概率急剧上升;
- 容量需要满足负载因子(元素数/容量)的合理范围,避免后续插入单个元素就触发扩容。
3是能容纳2个元素的最小符合规则的容量,因此最终调整为3而非2。
内容的提问来源于stack exchange,提问作者3rfan
相关产品推荐
相关产品推荐

