[英]Rust: Cost of Comparison
In Rust, is ==
not an O(1)
operation?在Rust中, ==
不是O(1)
操作吗?
How expensive is it to ==
two large, nearly identical Vec
s or BTreeMap
s? ==
两个大的、几乎相同的Vec
或BTreeMap
的代价是多少?
How does Rust perform this operation? Rust是如何进行这个操作的?
==
in Rust is not guaranteed to be O(1). ==
Rust 不保证是 O(1)。 For containers specifically, it may be much costlier.特别是对于容器,它可能要贵得多。
Both Vec
(actually slice, since it implements the underlying comparison for both vecs and slices) and BTreeMap
are O(n) where n
is the number of elements in the container. Vec
(实际上是切片,因为它实现了 vec 和切片的底层比较)和BTreeMap
都是 O(n),其中n
是容器中元素的数量。 Both however are O(1) where the sizes of the compared containers are different.然而,两者都是 O(1),其中比较容器的大小不同。
The code for BTreeMap
is here : BTreeMap
的代码在这里:
impl<K: PartialEq, V: PartialEq> PartialEq for BTreeMap<K, V> {
fn eq(&self, other: &BTreeMap<K, V>) -> bool {
self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b)
}
}
The code for slice is here :切片的代码在这里:
impl<A, B> SlicePartialEq<B> for [A]
where
A: PartialEq<B>,
{
default fn equal(&self, other: &[B]) -> bool {
if self.len() != other.len() {
return false;
}
self.iter().zip(other.iter()).all(|(x, y)| x == y)
}
}
Certain types are compared using faster memcmp()
( here ).某些类型使用更快的memcmp()
进行比较( 此处)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.