4 ms·
Can anyone comment on the performance of structural pattern matching in Python 3.10 for simple cases compared to if/elif? For example, say I am just checking fo
by WoodenChair 5y ago
Can anyone comment on the performance of structural pattern matching in Python 3.10 for simple cases compared to if/elif? For example, say I am just checking for which of several cases from an enum to diverge based on.
- benhoyt 5y agoI did a quick test of match vs if...elif for a basic enum switch, as well as a slightly more involved class/structural matching test. Results and code: https://gist.github.com/benhoyt/f648d6dd13ce112ba1a4422b175e6163 https://gist.github.com/benhoyt/f648d6dd13ce112ba1a4422b175e... For the enum switch, match generates very similar bytecode (use dis.dis to see) and the execution time is almost identical. For the structural matching, match is significantly slower, which surprised me a bit (it's almost twice the number of bytecode instructions). That said, we're down in the nanoseconds range -- use of this feature shouldn't be about ns-level performance, but code clarity. I suspect "match" will get faster over time as they add optimizations or specialized bytecode for it.