pattern matching as switch - case
Is it possible to implement upcomming pattern matching more like switch-case in C rather than like in Python in which it is powerful syntax sugar for if-else? My question araises, becase switch-case is much more performant in non-trivial examples and it will be really nice to use it instead of if-else and have improvements in performance because of that
14 Replies
There's no fundamental reason why a
match
statement would be slower than a switch
statement in Mojo, if you're using it for the same purpose.I think it's just that Python's
match
is very bad (lacking features, weird scoping rule, etc.), and given the restriction of Python the language, it can't do much better. It would be absurd if Mojo's match
is as bad.I don't understand how Python's match is just a powerful syntax sugar for if/else and switch case isn't.
Python's pattern matching has extensive pattern support, matching everything from tuples to arguments passed to classes
@Melody Daniel In low-level languages,
switch
statements sometimes compile to a jump table, rather than a sequence of conditional branches. (i.e. if/else)And in a proper language like ML (sorry, can't lie), if/else should be syntax sugar for match.
Is there an if/else in CPU instructions? There are conditional jumps.
Anyway, Rust has pattern matching, does this compile to less efficient branching?
It really depends upon what the patterns are. Certain patterns can compile to jump tables.
Particularly, patterns based on small integer literals, or sum types (which are encoded as integers)
I see. Well, Modular is aiming for maximum performance and so I'm sure they'll do something do something aimed towards that goal
![No description](https://cdn.answeroverflow.com/1205798298246455306/IMG_20240210_135007_162.jpg)
![No description](https://cdn.answeroverflow.com/1205798298473201724/IMG_20240210_135006_616.jpg)
Both compile to same assembly
Interesting.
It is possible to use in Mojo both jump tables and conditional branches in pattern matching? This seems to be the best approach
Hmm, I am curious if jump table here will be faster. Creating it gives overhead and here are only 2 conditions, so maybe classical jums performs better
Most languages (with pattern matching) do both, jump table only when there are more than a few cases. More advanced features like pattern guard (
pat when pred -> expr
) also requires conditional jumps.
Simply put: there is a whole literature about how to compile pattern matchings efficiently, and there are many tricks to be used.
Of course it’s the case. Like I said above, if/else is syntax sugar for match. In Rust, bool is a enum, and matching on enum cases got lowered into SwitchInt
(think C switch
) in MIR (Rust’s mid level IR).I like sweet syntax... all of Python is about that. With the aim of improving human readability. And if Mojo can implement Python
match
for free, I think it would be perfect.