简体   繁体   中英

Rust: Cost of Comparison

In Rust, is == not an O(1) operation?

How expensive is it to == two large, nearly identical Vec s or BTreeMap s?

How does Rust perform this operation?

== in Rust is not guaranteed to be 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. Both however are O(1) where the sizes of the compared containers are different.

The code for BTreeMap is here :

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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM