Which of the following is faster?
1.
def is_even(num: int):
if num%2==0:
return True
else:
return False
def is_even(num: int):
if num%2==0:
return True
return False
I know you can technically do this:
def is_even(num: int):
return n%2==0
But for the sake of the question, ignore this solution
>Solution :
Compare the byte codes shown by dis.dis().
if/else version:
2 0 LOAD_FAST 0 (num)
2 LOAD_CONST 1 (2)
4 BINARY_MODULO
6 LOAD_CONST 2 (0)
8 COMPARE_OP 2 (==)
10 POP_JUMP_IF_FALSE 16
3 12 LOAD_CONST 3 (True)
14 RETURN_VALUE
5 >> 16 LOAD_CONST 4 (False)
18 RETURN_VALUE
20 LOAD_CONST 0 (None)
22 RETURN_VALUE
if/return version:
2 0 LOAD_FAST 0 (num)
2 LOAD_CONST 1 (2)
4 BINARY_MODULO
6 LOAD_CONST 2 (0)
8 COMPARE_OP 2 (==)
10 POP_JUMP_IF_FALSE 16
3 12 LOAD_CONST 3 (True)
14 RETURN_VALUE
4 >> 16 LOAD_CONST 4 (False)
18 RETURN_VALUE
They’re idential up to byte 18. The if/else version has an extra 2 instructions to return None if neither of the blocks return from the function.
This is wasted memory, but won’t affect the running time because both the if and else blocks do return. An optimizing compiler would realize that both if and else end with return so this isn’t needed, but the Python compiler doesn’t bother (apparently this has been fixed between Python 3.9.2 and 3.11.1).