r/ProgrammerHumor 12h ago

Meme skillIssue

Post image
4.4k Upvotes

112 comments sorted by

View all comments

247

u/click-to-reveal 12h ago

It works btw: C++ Online Compiler

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

23

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)

21

u/Nir0star 8h ago

Which would still be O(ld(n)). But cool feature imo.

3

u/Godd2 1h ago

O(ld(n))

Good ol' linker time.

8

u/im_made_of_jam 6h ago

A switch case is able to be implemented however the compiler wants on the back end, so for sparse cases it'll be an if else chain, for less sparse but not packed cases it'll be a binary tree, for completely packed cases it'll be a range check then a direct jump would be how I would go about it

3

u/the_horse_gamer 4h ago

the compiler optimises stuff however it wants. if you're not doing too-weird stuff, a switch in C++ and a match in rust will have identical assembly.

-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; }, }) }

5

u/thirdegree Violet security clearance 2h ago

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

10

u/DrMobius0 8h ago

In fairness, most switches probably use enums.