to pass self or not to pass self

Patrick Maupin pmaupin at gmail.com
Wed Mar 17 17:21:44 EDT 2010


On Mar 17, 2:55 pm, Terry Reedy <tjre... at udel.edu> wrote:
> On 3/17/2010 1:35 AM, Patrick Maupin wrote:
>
> >>>> def a(s, count, lenfunc):
> > ...     for i in xrange(count):
> > ...        z = lenfunc(s)
> > ...
> >>>> >>>  a('abcdef', 100000000, len)
> >>>> >>>  a('abcdef', 100000000, str.__len__)
> > Running cPython 2.6 on my machine, len() runs about 3 times faster
> > than str.__len__().  The overhead of checking that an object is usable
> > with a particular class method far outweighs the cost of creating the
> > bound method!
>
> Wow, this so surprised me, that I had to try it with 3.1 (on winxp), and
> got a similar result (about 2.6x longer with str.__len__). This is a
> real lesson in measure, don't guess, and how premature 'optimization'
> may be a pessimization. Thanks.
>
> Terry Jan Reedy

Actually, I think I overstated my case -- there is some special logic
for len and built-in objects, I think.   I can see the same thing with
normal attributes on subclasses of object(), but not nearly as
dramatic.  In any case, your conclusion about this being a lesson in
"measure, don't guess" holds, with the additional caveat that, if it
matters, you need to somehow do some additional measurements to make
sure you are measuring what you think you are measuring!

Pat



More information about the Python-list mailing list