Difference in performance of alternative switches in Python

I read several articles about alternatives to switch statements in Python. Mostly using dicts instead of a lot of if and elif. However, in reality, no one answers the question: do you have the best performance or efficiency? I read a few arguments that if elifs would need to test each statement and become ineffective with many ifs and elif. However, using dicts turns around this, but you need to create new modules for calling, which in any case cancel the performance gain. The only difference is that it is ultimately readable.

Can anyone comment on this, is there any difference in the long run? Does anyone regularly use an alternative? The only reason I ask is that I will end up with 30-40 elif / if and possibly more in the future. Any input is appreciated. Thanks.

+3
source share
6 answers

dict , , , dict O (1), ( ;-). " ", , , , dict, , , - , , .

, timeit . : , , , - - , , !)

, , , , , SO ! -)

+8

, . , , . ( ), 30-40 elif - , - . , , , - .

+6

/ - " ".

- timeit, python.

, , switch. , . , , .

( - ) , .

+3

, , dict Python. switch, Python ( ), .

dicts Python. CPython dicts - , -. - O (1), elif, O (n). (30-40, , , ). , , dicts .

, . ( Python-!), , . , , , .

+1

, if, , . , , if . , , , . .

0

(. ). , . : , .

0

Source: https://habr.com/ru/post/1722194/


All Articles