I have a function implemented as a lambda
as well as a if elif ...
and compared the execution time :
light = lambda c, v: {'turn on': 1,
'turn off': 0,
'toggle': (v+1)%2}[c]
def l(c, v):
if c == 'turn on':
return 1
elif c == 'turn off':
return 0
elif c == 'toggle':
return (v+1)%2
return v
t = Timer(lambda: light('turn on', 0))
print('light: ' + str(t.timeit(number=23163958)))
t = Timer(lambda: l('turn on', 0))
print('l: ' + str(t.timeit(number=23163958)))
The output is:
light: 8.976719211001182
l: 3.9458757909887936
Why is the if
statement almost twice as fast? Is it possible to increase the performance even more? I have to execute the function over 23 million times.
According to this I thought the dict lookup would be faster: https://stackoverflow.com/a/15925086/2014080