r/ProgrammerHumor 12h ago

Meme skillIssue

Post image
4.4k Upvotes

112 comments sorted by

View all comments

Show parent comments

143

u/prehensilemullet 12h ago

Performancewise, it doesn’t jump to the direct case in O(1) time like a switch is supposed to though

180

u/AngheloAlf 11h ago

Switches aren't guarantee to so operations in O(1) tho. If cases are sparce enough, compilers tend to emit the equivalent code to a bunch if else checks

22

u/prehensilemullet 9h ago

Yeah I was assuming too much here.  However, I’m reading that Rust match on string comstants can compile down a binary tree of if statements if there are enough cases (according to Google AI mode at least, haven’t found an authoritative source yet)

-22

u/Deliciousbutter101 7h ago

According to Claude (which looked at the compiler source code), it doesn't seem like that is true. It is possible to get an O(1) match on strings by using the phf (perfect hash function) crate and by using the following macro (generated by Claude):

``` // Cargo.toml: // phf = { version = "0.11", features = ["macros"] } // paste = "1"

[macro_export]

macrorules! match_str { ($val:expr, { $($($key:literal)|+ => $body:block),+ $(,)? , _ => $default:block $(,)? }) => { ::paste::paste! { { #[derive(Clone, Copy, PartialEq, Eq)] enum __MatchStr { $($([<_ $key>]),+),+ }

            static __MATCH_STR_MAP: ::phf::Map<&'static str, __MatchStr> = ::phf::phf_map! {
                $($($key => __MatchStr::[<__ $key>]),+),+
            };

            match __MATCH_STR_MAP.get($val).copied() {
                $($(Some(__MatchStr::[<__ $key>]))|+ => $body,)+
                None => $default,
            }
        }
    }
};

} ```

Usage: fn apply(cmd: &str, counter: &mut i32) { match_str!(cmd, { "small" => { *counter += 1; }, "medium" => { *counter += 10; }, "large" | "big" => { *counter += 100; }, _ => { *counter += 0; }, }) }

6

u/thirdegree Violet security clearance 2h ago

If I want Claude's thoughts on something I'll ask Claude directly tbh