An excellent comparison of If/Else vs Dictionary is provided at StackOverflow. To summarize, using a dictionary ...
- is built-in
- is pythonic
- requires less boilerplate code
- has O(1) complexity, compared to the if-else linear O(n) complexity
ifs = []
dict = []
for i in range(60):
string = 'str%d' % i
ifs.append(' %sif str == "%s": return %d' % ('el' if i else '', string, i))
dict.append('"%s": %d' % (string, i))
print 'dict = {', ','.join(dict), '}'
print 'def with_dict(str):'
print ' return dict[str]'
print 'def with_if(str):'
print '\n'.join(ifs)
print '''
import timeit
def test_dict():
for i in range(60):
with_dict("str%d" % i)
def test_if():
for i in range(60):
with_if("str%d" %i)
print 'dict:', timeit.timeit(test_dict, number=10000)
print 'if: ', timeit.timeit(test_if, number=10000)'''
Assuming the script is named dict_perf_test.py, it's run as
python dict_perf_test.py | python.On a basic Lenovo T430, it gives:
dict: 0.429204940796
if: 1.22928714752
Dictionary mapping wins.
No comments:
Post a Comment