python 2.7 fastest dict acces for missing keys -



python 2.7 fastest dict acces for missing keys -

if d dict, python docs provide method:

dict.get = get(...) d.get(k[,d]) -> d[k] if k in d, else d. d defaults none.

another famous pattern is:

try: d[k]: except: d

but in benchmarks (done timeit), have found next approach best:

if k in d: d[k] else: d

the try/except pattern fastest if no exceptions raised, if no exceptions raised, don't need pattern. need refactor code, written lot of .get()'s, because need squeeze performance on limited system. right or wrong? why try/except pattern recommended when looks it's slowest?

looks d[k] if k in d else d pattern twice faster .get, @ to the lowest degree usages.

.get

$ python -m timeit -s 'd={}; k=xrange(0,100000)' 'd.get(k)' 10000000 loops, best of 3: 0.0934 usec per loop

if/else

$ python -m timeit -s 'd={}; k=xrange(0,100000)' 'd[k] if k in d else none' 10000000 loops, best of 3: 0.0487 usec per loop

python python-2.7 dictionary

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -