Jeremy Hylton : weblog : 2003-05-06

Attribute Access Microbenchmark

Tuesday, May 06, 2003

I tried out the new timeit module today. How long does it take to access an attribute on a class instance? I tried three variations: a classic class, a new-style class, and a new-style class with slots.

The class had 16 attributes named "a1" .. "a8" and "b1" .. "b8". The timeit test statement was just "obj.b1". The three results are:

Regular new-style class 0.24
New-style class w/slots 0.18
Classic class 0.16

Measurement: 200,000 iterations on my laptop.

Conclusion: Attribute lookup on a new-style class is 50% slower than on a classic class. The use of slots speeds up lookup and gets closer to the classic class speed.

What if we add inheritance to the mix? I created subclasses of the original classes. The classic and new-style class had no body (just a pass). The slot-style class said __slots__ = "a1", just because it needed to declare that it used slots. Then I repeated the same steps, so I could test with one base class and two.

Regular new-style class 0.26 0.29
New-style class w/slots 0.25 0.31
Classic class 0.16 0.16

The new-style class is a little slower, but the slot-style class is a lot slower. The slot-style class is now slower than the new-style class without slots. The classic class stayed the same. It looks like slot-style classes continue to get worse as the inheritance hierarchy gets deeper. The exact behavior depends on how many base classes must be traversed before the slot descriptor is found.