performance of dictionary lookup vs. object attributes

Fredrik Lundh fredrik at pythonware.com
Fri Aug 25 09:24:08 EDT 2006


Andre Meyer wrote:

> So, what it means is that the test is not meaningful, because of the
> different way that object attributes are accessed (not as o.x, which
> could be compiled).

correct, but you may be overestimating what the compiler can do.  here's
the byte code for the various cases:

  # x.attr
  2           0 LOAD_FAST                0 (x)
              3 LOAD_ATTR                0 (attr)
              6 POP_TOP

  # getattr(x, "attr")
  3           7 LOAD_GLOBAL              1 (getattr)
             10 LOAD_FAST                0 (x)
             13 LOAD_CONST               1 ('attr')
             16 CALL_FUNCTION            2
             19 POP_TOP

  # x.__getattribute__("attr")
  4          20 LOAD_FAST                0 (x)
             23 LOAD_ATTR                2 (__getattribute__)
             26 LOAD_CONST               1 ('attr')
             29 CALL_FUNCTION            1
             32 POP_TOP

the LOAD_ATTR instruction uses a much faster code path to get at the
internal dictionary, while the getattr() and __getattribute__ forms needs
to do extra work to get to the actual attribute lookup.

> Nevertheless, the general impression remains that dicts *are* faster
> than objects, because attribute lookup uses dicts itself. Is that
> correct?

correct.  once the interpreter gets to actually do the lookup, the performance
is identical (and the dictionary implementation is *extremely fast*).  it's the stuff
that needs to be done to get there that differs.

</F> 






More information about the Python-list mailing list