Performance penalty for using classes?
tjreedy at udel.edu
Sun Jan 12 18:52:34 CET 2003
"Miki Tebeka" <tebeka at cs.bgu.ac.il> wrote in message
news:33803989.0301120004.76e09b9a at posting.google.com...
> Hello All,
> I need my M.Sc. to run fast but I don't want to recode it in C.
> I've noticed that using classes can cause my code to run about 30%
> (See the below tests)
In this particular case, you could speed your code by getting rid of
the unnecessary get and set functions (function calls are somewhat
expensive) and access the attributes directly. OO purists may object,
but you asked for speed, and _set/getattr__ can be used when get/set
otherwise become needed due to internal changes.
def __init__(self, x, y):
self.x = x
self.y = y
while iterations > 0:
d = Dot(random.random(), random.random())
x = d.x
y = d.y
d.x = y
d.y = x
iterations -= 1
Note: breaking the tuple assignment into separate statements is less
convenient, but avoids creating a tuple only to discard it and is
Terry J. Reedy
More information about the Python-list