Mehranjp73
Mehranjp73

Reputation: 521

What is the fastest way to check if something exist in a vector in Rust?

I have a large list of data in a text file. I read the text file and added each line to a vector, but when I check if some string exists in that vector using contain method, the app slows down. I saw the same kine of functionality in python with pickle which it was really fast. How can make checking if something exist in a vector faster?

Upvotes: 2

Views: 4247

Answers (2)

Mehranjp73
Mehranjp73

Reputation: 521

I implemented binary search and it got really fast. It's kinda too good to be true.

fn main() {

    let mut  v: Vec<String> = Vec::new();
    v.push("afd".to_string());
    v.push("zdgdg".to_string());
    v.push("bvbvb".to_string());

    v.sort_unstable();

    println!("{:?}", v);
    match v.binary_search(&"bvbvb".to_string()) {
        Ok(u) => {
            println!("yes {}", u)
        }
        Err(e) => {
            println!("No {}", e)
        }
    }
}

Upvotes: 2

transistor
transistor

Reputation: 1660

In order for .contains() to find an element in the Vec, it must traverse each element and compare the element to the search string to check if it's there. The easiest optimization you can make is to use a HashMap instead, where the key is the string you want to search for, and the value can be () since it's not important. You can then search for a given string with .get() and either get Some(()) if it's contained in the map or None otherwise. It's possible to iterate over all elements of a hashmap, so you can still retrieve all the stored values, but you'll gain a much faster ability to search

Upvotes: 4

Related Questions