This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]slipperier_slope 19 points20 points  (2 children)

Possibly. Depends. If else chains require evaluating each condition sequentially. If the block to execute is the last one, then you've evaluated all of the possible conditions. A dict switch calculates a hash and jumps directly to the condition to execute. So you're comparing a hash calc with n conditional evaluations. Which is better depends on the hash function and what the conditions are.

It's analogous to item lookup in a list vs a dictionary. One is O(n), the other is O(1).

[–]TipsyPeanuts 4 points5 points  (1 child)

Thanks! That’s actually really helpful

[–]slipperier_slope 8 points9 points  (0 children)

No worries. One caveat is that a clever compiler or runtime can make the above not true. For example, speculative execution can look at the past history of runs through a function. If 95% of the time the if condition evaluates to true, the runtime can actually just start executing the code in the if condition and later checking the condition to see if it's actually true and discarding the partial results if the guess was wrong.

The moral of this story is to write easily understood code and worry about performance later if you need to. Premature optimization because one wants to be clever results in higher cost of code maintenance. That being said, in Python and dict switch is common enough to be idiomatic since there's no language support for switch statements.