Or are you seeing something I'm missing?
Yes. You're missing the implicit jump.
It's :
- Test the first condition, it's false
- Test the second condition, it's true
- do something
- Test the third condition, it's false
- do whatever is after that.
versus :
- Test the first condition, it's false.
- Test the second condition, it's true.
- do something.
- jump outside of the /if/ structure.
- do whatever is after that.
The
if
/
elif
structure is a better approach and a time saver one, as long as the order of each condition is thought seriously.
If the most common condition is the last of your
if
/
elif
structure, you'll gain nothing. But at the opposite, if you put it as first condition, you avoid a lot of unnecessary tests.
This said, globally speaking, with each condition having an equal chance to happen, the gain will be sensible, especially if you have a lot of tests in the structure.
With 4 calls, a pure
if
structure of four conditions will lead to 16 tests
This while the same, but expressed as an
if
/
else
structure, would only need 10 tests.
It's a geometrical progression, so the more conditions you'll have, the more you'll gain if you use the
if
/
elif
structure. But the gain is sensible even with the most basic structure. With an equal distribution of the values, even something as simple as :
Code:
if a is True: do something
else: do another thing
would be 1/4 faster than :
Code:
if a is True: do something
if a is False: do another thing
After, it don't mean that the pure
if
approach is effectively bad. It's just slower, but to be effectively sensible on a modern computer, you need to have a lot of complex conditions, and to call them frequently.
So, it's only to avoid in screens, since they are refreshed more or less once every two seconds. Yet only if really you use a tons of complex conditions.