id() collisions on bound methods [was: metaclass and customization with parameters]

Jeff Epler jepler at unpythonic.net
Tue Oct 5 22:46:47 EDT 2004


On Tue, Oct 05, 2004 at 10:56:59PM -0300, Carlos Ribeiro wrote:
> ...but even so, what doesn't make sense to me is if it's worth to do
> it, at each and every method invocation. I really don't know, and I'm
> curious, but I have no clue where to start looking for it, or how to
> measure the impact on real-time performance.

In the Olden Days, "caching" bound methods would have led to cycles
that were never collected.  Nowadays, there's a cyclic GC collector,
so if that was the killer for this idea maybe it's worth revisiting.

Given
    class C:
        def f(self): pass
    c = C()
    f = c.g = c.f
    
it's fastest (1.4 usec/loop) to call f() [which you'd do in a tight
loop], slower (1.66 usec/loop) to call c.g() [which is what you're
proposing Python should do automatically] and slowest (2.01 usec/loop)
to call c.f() [what happens today if you don't take special steps].

For new-style classes, the timings are similar, but with less advantage
to c.g().  1.39, 1.87, 1.98.

When the attribute doesn't reside on the class, but on a base class,
things get a little worse.
    class C(object):
        def f(self): pass

    for i in range(10):
        class C(C): pass

    c = C()
    f = c.g = c.f
gives these timings: 1.38, 2.83, 2.97.  With old-style classes, 1.4,
1.71, 3.88.  Here's where the big difference lies---when you've got a
lot of base classes, and the method isn't found until many of them are
searched.

Perhaps someone could devise a metaclass that does bound method caching.
In a few situations, it might be worth having, but I'm not sure if in
those situations a little
    c.f = c.f
in __init__, or manual hosting like 'f=c.f' is not just as appropriate.

Jeff
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20041005/bdf05482/attachment.sig>


More information about the Python-list mailing list