performance of dictionary lookup vs. object attributes

Peter Otten __peter__ at web.de
Fri Aug 25 08:48:00 EDT 2006


Andre Meyer wrote:

> Hi all
> 
> I was wondering about the performance comparison of either using a
> dictionary or an object for a large collection of "things". Therefore
> I have run the attached test. I create a dictionary and an object.
> Both get the same number of items/attributes, respectively. Then, for
> both the values are read often (iterations).
> 
> Here are the results:
> 
> attributes 100
> iterations 1000000
> dic 25.515999794
> obj 138.570000172
> 
> Is the test meaningful and are you surprised by the results? I am,
> actually, because I would have assumed that attribute access with an
> object should be faster because lookup can be precompiled.

I think it is not meaningful as obj.__getattribute__("attribute") is
significantly slower than obj.attribute. dict lookup is still significantly
faster:

$ python -m timeit -s'class A(object): pass' -s 'a = A(); a.alpha = 42'
'a.__getattribute__("alpha")'
1000000 loops, best of 3: 0.674 usec per loop

$ python -m timeit -s'class A(object): pass' -s 'a = A(); a.alpha = 42'
'a.alpha'
1000000 loops, best of 3: 0.215 usec per loop

$ python -m timeit -s'd = dict(alpha=42)' 'd["alpha"]'
10000000 loops, best of 3: 0.167 usec per loop

Peter




More information about the Python-list mailing list