Reputation: 1244
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
Upvotes: 0
Views: 1056
Reputation: 5006
The problem is that each call of the lambda you instantiate the dictionary again, this takes time. If the dictionary is just being referenced, not created, it runs quicker than the conditionals.
Some simplified code to demonstrate the point.
from timeit import Timer
d = {'turn on': 1, 'turn off': 0}
light = lambda c : d[c]
t = Timer(lambda: light('turn on'))
print('light: ' + str(t.timeit(number=23163958)))
# light: 3.66314601898
Upvotes: 1