Performance penalty for using classes?
Hans Nowak
wurmy at earthlink.net
Sun Jan 12 13:04:20 EST 2003
Miki Tebeka wrote:
> 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%
> slower.
> (See the below tests)
>
> --- class_test.py ---
> #!/usr/bin/env python
> import random
>
> class Dot:
> def __init__(self, x, y):
> self._x = x
> self._y = y
>
> def x(self):
> return self._x
>
> def set_x(self, x):
> self._x = x
>
> def y(self):
> return self._y
>
> def set_y(self, y):
> self._y = y
These four methods serve no purpose and only incur overhead. Replace this with:
class Dot:
def __init__(self, x, y):
self.x = x
self.y = y
Now, replace calls like "d.x()" with "d.x", and "d.set_x(z)" with "d.x = z".
> def test_class(iterations):
> while iterations > 0:
> d = Dot(random.random(), random.random())
> x, y = d.x(), d.y()
> d.set_x(y)
> d.set_y(x)
It looks like this can be replaced with:
d.x, d.y = d.y, d.x
No need for temporary variables and redundant method calls. :)
Now try running this code again. On my box, they both time at around 2.8s.
Of course, after this rewrite, you can still use Psyco, Python 2.3a1, and a
faster computer. ;-)
HTH,
--
Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA=='))
# decode for email address ;-)
The Pythonic Quarter:: http://www.awaretek.com/nowak/
Kaa:: http://www.awaretek.com/nowak/kaa.html
More information about the Python-list
mailing list