Achieving optimal performance in code

Is there any difference between the following two expressions\statements?

def func1(a):
    return a == 'TRUE'
def func2(a):
    return True if a == 'TRUE' else False

Well, both of them do the same thing but interestingly, the former one is faster in terms of performance by atleast one CPU cycle! Let’s tear into assembly language of each of these funcs to see the real difference …. Smile

Assembly of Func1 >>

  2           0 LOAD_FAST                0 (a)
              3 LOAD_CONST               1 ('TRUE')
              6 COMPARE_OP               2 (==)
              9 RETURN_VALUE

Assembly of Func2 >>

  2           0 LOAD_FAST                0 (a)
              3 LOAD_CONST               1 ('TRUE')
              6 COMPARE_OP               2 (==)
              9 JUMP_IF_FALSE            5 (to 17)
             12 POP_TOP
             13 LOAD_GLOBAL              0 (True)
             16 RETURN_VALUE
             17 POP_TOP
             18 LOAD_GLOBAL              1 (False)
             21 RETURN_VALUE

JUMP_IF_FALSE evaluation takes the extra cpu cycle in this case.

leave your comment