Performance penalty for using classes?

Terry Reedy tjreedy at
Sun Jan 12 18:52:34 CET 2003

"Miki Tebeka" <tebeka at> wrote in message
news:33803989.0301120004.76e09b9a at
> 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%
> slower.
> (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.

class Dot:
    def __init__(self, x, y):
        self.x = x
        self.y = y

def test_class(iterations):
    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
slightly faster.

Terry J. Reedy

More information about the Python-list mailing list