Tuesday, October 22, 2013

If/else vs Dictionary

For some reason the issue of using if/else statements vs dictionary maps pops up regularly here.  It shouldn't as there's no reason to use an if/else ladder vs using a dictionary.  The only argument that developers can give for always arguing for If/Else ladders is that they're easier to read and understand what's going on.  Given the redundant code and slower performance, this is purely a personal opinion than a viable reason to prefer If/Else statements over dictionaries.

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
There's even a profile script to compare if/else usage vs dictionary usage.

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