[XML-SIG] foo.bar vs. foo.get_bar()
Dieter Maurer
dieter@handshake.de
Sat, 6 Nov 1999 20:13:14 +0100 (CET)
--Multipart_Sat_Nov__6_20:13:14_1999-1
Content-Type: text/plain; charset=US-ASCII
uche.ogbuji@fourthought.com writes:
> Any class with __[g/s]etattr__ is automatically slower, whether or not the
> methods are actually used. This is for a simple reason: without these hooks,
> attribute access involves basic C pointer magic within the interpreter, which
> is of course blazingly fast. Whenever the hooks are present, the interpreter
> must invoke the hooks for every attribute access, even if it turns out the
> hooks aren't used. As I've mentioned before, round trips from the C engine to
> Python interpreted code incur a steep performance penalty.
I think this is not generally true for "__getattr__":
reason: "__getattr__" is only used, if an attribute cannot be found
by "normal" lookup.
The attached script, for example produced the following timing:
__main__.C1 0.43
__main__.C2 0.43
__main__.C2 0.44
__main__.C1 0.43
There is no significant difference between C1 (without)
and C2 (with __getattr__).
This only changes, when attributes are looked up that are not
found by looking into the __dict__, e.g. because they do
not exist at all.
- Dieter
--Multipart_Sat_Nov__6_20:13:14_1999-1
Content-Type: application/x-python
Content-Disposition: attachment; filename="x.py"
Content-Transfer-Encoding: 7bit
'''measuring the effect of 'getattr'.'''
import time
class C1:
a=1
class C2:
a=2
def __getattr__(self,k): pass
def test(c,n=10000):
i= 0
s= time.clock()
while i < n:
c.a; c.a; c.a; c.a; c.a; c.a; c.a; c.a; c.a; c.a
i= i+1
e= time.clock()
print c, e-s
test(C1)
test(C2)
test(C2)
test(C1)
--Multipart_Sat_Nov__6_20:13:14_1999-1--