I was reviewing some code earlier and the developer wrote an inline if/else rather than a get() to retrieve an element from a list if it exists (otherwise give it a default value). I decided to spring some timeit code on repl and was pretty confused by the result. The if/else takes 1/3 the time of the get().

Here is the repl code, and below is the code in the repl as well as the result for posterity:

import timeit

D = {"a": 1, "b": 2, "c": 3}

def ef(): return D['a'] if 'a' in D else 1

def gt(): return D.get('a', 1)

print "gt1", timeit.timeit(gt, number=10000)
print "ef1", timeit.timeit(ef, number=10000)
print "ef2", timeit.timeit(ef, number=10000)
print "gt2", timeit.timeit(gt, number=10000)

and the results:

gt1 0.0659999847412
ef1 0.0239999294281
ef2 0.0249998569489
gt2 0.0539999008179

and a visual of 10 iterations of the above timeit calls, where the result has been multiplied by 10000 for representation purposes

visual of 10 iterations

Related posts

Recent Viewed