Skip to content
Advertisement

Python Match Case (Switch) Performance

I was expecting the Python match/case to have equal time access to each case, but seems like I was wrong. Any good explanation why?

Lets use the following example:

JavaScript

And define a quick tool to measure the time:

JavaScript

If we run each 10000000 times each case, the times are the following:

JavaScript

Just wondering why the access times are different. Isn’t this optimised with perhaps a lookup table?. Note that I’m not interested in other ways of having equals access times (i.e. with dictionaries).

Advertisement

Answer

PEP 622 The “matchcase” functionality is developed to replace the code like this:

JavaScript

with code like this:

JavaScript

While it may be equivalent to a dict lookup in the most primitive cases, in general it is not so. Case patterns are designed to look like normal python code but actually they conceal isinsance and len calls and don’t execute what you’d expect to be executed when you see code like Node().

Essentially this is equivalent to a chain of if … elif … else statements. Note that unlike for the previously proposed switch statement, the pre-computed dispatch dictionary semantics does not apply here.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement