class C: vs class C(object):

Klaas mike.klaas at gmail.com
Mon Jul 23 14:48:19 EDT 2007


On Jul 20, 5:47 am, Hrvoje Niksic <hnik... at xemacs.org> wrote:
> "sjdevn... at yahoo.com" <sjdevn... at yahoo.com> writes:
> > In particular, old-style classes are noticeably faster than
> > new-style classes for some things (I think it was attribute lookup
> > that surprised me recently, possibly related to the property
> > stuff...)
>
> Can you post an example that we can benchmark?  I ask because the
> opposite is usually claimed, that (as of Python 2.4 or 2.5) new-style
> classes are measurably faster.

Why do people ask for trivial examples?

$ cat classes.py
class Classic:
        def __init__(self):
                self.attr = 1

class NewStyle(object):
        def __init__(self):
                self.attr = 1

$ python -m timeit -s 'from classes import *; c = Classic()' 'c.attr'
<timeit-src>:2: SyntaxWarning: import * only allowed at module level
1000000 loops, best of 3: 0.182 usec per loop

$ python -m timeit -s 'from classes import *; c = NewStyle()' 'c.attr'
<timeit-src>:2: SyntaxWarning: import * only allowed at module level
1000000 loops, best of 3: 0.269 usec per loop

New style classes have more machinery to process for attribute/method
lookup, and are slower.

There are very few algorithms for which attribute access is the
bottleneck however (seeing as how easier they can be extracted out of
inner loops into locals, which are much faster than attribute access
on either type of class).

Using old-style classes for performance is a useful hack for python
perf wizards, but is a dangerous meme to perpetuate.

-Mike




More information about the Python-list mailing list