Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is using else faster than returning value right away?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading