Vector/Slice data checking

I have these logic in my company code, where they have list of data to be filtered out in business logic.

pub async fn filter(param: &str) -> Result((),String) {
...
    if vec![
        "rule_1",
        "rule_2",
        "rule_3",
    ].contains(param) { 
        /// do something
    }
...
}

I don't know detail about rust compiler, but, does rustc make some optimization to this constants rule checking?, I know vector does allocate on heap, if compiler does nothing about it then there'll be heap alloc at every api calls, right?, do I have to move it into constant/static?

You could just use a regular array instead.

1 Like

Yeah, my current solution is that I make the rules as constant array. Other as static for reference data.

Sometimes LLVM will be smart enough to optimise out Vec's allocation, but it's not guaranteed.

If you use a normal array which never gets modified, the compiler should automatically promote it to a const. That way you aren't setting aside memory for the array and populating it every time the function is called, and you don't need to explicitly write out the array's type like you would if it were a static or const variable.

Another option is to use the phf crate's Set type to create an immutable, static lookup table which will give you really fast lookups.

2 Likes

Thanks for suggestion. I think it's good now to just declare it as constant array, or even static.

You could also do something like

if matches!(param, "rule_1" | "rule_2" | "rule_3") {

if you want to check against multiple string literals.

(If you need to re-use the set, though, a const is probably best.)

2 Likes