For the following two code:
if a and b:
then do something
if a:
if b:
then do something
What is the difference between these two statements in terms of semantics and the time it takes to execute? Do not both of them always evaluate the same? And is one of them faster than the other (I am not asking asymptotically, not the big O notation)?
Byte code with and:
7 0 LOAD_GLOBAL 0 (a)
2 POP_JUMP_IF_FALSE 8
4 LOAD_GLOBAL 1 (b)
6 POP_JUMP_IF_FALSE 8
8 >> 8 LOAD_CONST 0 (None)
10 RETURN_VALUE
Nested statement:
10 0 LOAD_GLOBAL 0 (a)
2 POP_JUMP_IF_FALSE 8
11 4 LOAD_GLOBAL 1 (b)
6 POP_JUMP_IF_FALSE 8
12 >> 8 LOAD_CONST 0 (None)
10 RETURN_VALUE
Edit: If I'm not making a mistake, they are generating exactly the same bytecode.
CodePudding user response:
They have the exact same semantics.
See 6.11. Boolean operations in the language specification:
The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.
It selects exactly one of the suites by evaluating the expressions one by one until one is found to be true (see section Boolean operations for the definition of true and false); then that suite is executed (and no other part of the if statement is executed or evaluated).
No tricky combination of implementations of __bool__
and __and__
(which is the operator &
, not and
) methods can change this.
I wouldn't be concerned about any performance difference; if you need to worry about such nano-optimizations, don't use Python in the first place.
CodePudding user response:
When you are writing code, you should look first that you can understand the code later on. So I would choose the first type of the if-statement. I think, you would execute this code on a rather powerful PC and you wouldn't notice any speed differences at all.
Just look, that the code is clean and readable to ensure, that you do not make extra long complicated logic. Bad ways of logic implementation will take much longer to execute.
CodePudding user response:
The semantics are exactly the same. How they are interpreted, and specifically how fast the interpretation will be depend on the specific interpreter/compiler (i.e. on the python distribution).
As a side note, if you are not interested in asymptotic complexity, then you already have your answer: they run in perceivably the same amount of time.