One Python 2.1 idea

Thomas Wouters thomas at xs4all.net
Tue Dec 26 08:00:32 EST 2000


On Tue, Dec 26, 2000 at 10:03:41AM +0100, Alex Martelli wrote:
> <rturpin at my-deja.com> wrote in message news:9292tn$jka$1 at nnrp1.deja.com...
>     [snip]
> > Second, a question. Consider the invocation of a method,
> > such as:
> >
> >     x.foo()
> >
> > Does this really cause the lookup of the string "foo"
> > in x's namespace dictionary? The first time? Every time?
> 
> Yes, and yes.  No implicit caching.

Actually, it's even worse :) Methods are never stored in an instance's dict,
but are created 'on the fly' from the class's unbound method. The binding of
the method isn't too expensive, but it isn't totally free either (if
anything, it's a dict 'miss' and an aditional dict lookup in the class's
dict. More than one if you use deep or multiple inheritance (or both.))

You *can* speed it up, by doing 'x.foo = x.foo' somewhere early in your call
chain :) I experimented with this sometime during 2.0 development, but doing
this for every call (by adjusting instance_getattr2 to store bound methods
in the instance dict after creating them) proved only a marginal (and
disputable) improvement, and broke the pickle modules (because bound methods
can't be pickled.) And I'm not sure if the benifit is large enough to
actually build a framework of caching (which Python lacks entirely,
currently) and use it in the few places that might use it.

But if your code can cope with bound methods being stored in instance dicts
(that is, you don't use pickle in any form :) and you use deep or wide
inheritance, you might benifit from this 'optimization' by doing it
manually.

-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list