7

Disclaimer

I'm currently learning Java and I came across if-else and switch statement, and I learned Switch statement is slightly faster than if-else statement.

I'm familiar that Python adds a lot of boilerplate whenever we are creating something (defining functions and stuff) which can be seen by disassembling them using dis function.

Question:

Is match statement faster than if-else in Python? Is it more efficient to use it instead of traditional if-else statements?

In case you are unfamiliar with match statements, here's the link to PEP 636 -- Structural Pattern Matching tutorial.

Gagan Deep Singh
  • 372
  • 3
  • 13

1 Answers1

0

Yes, as far as I know, match/case structures are generally faster than if/elif/else structures. Use them wherever possible over if/elif/else structures. Match/case structures can check if a variable is equal to a value, but they cannot do complex conditions, so you will still be using if/elif/else structures quite a lot (e.g., if var and not var2: is only possible with an if/elif/else structure).