Thursday, January 31, 2008

Favorite Python Optimizations: Slots

If you are using any objects in Python, here is a quick way to knock a couple of seconds off the execution time - add slots. This is maybe the easiest optimization mod ever. It doesn't produce massive gains, but every little bit helps. So for a basic object like

class MyClass:
def __init__(self, var1, var2, var3):
self.myVar1 = var1
self.myVar2 = var2
self.myVar3 = var3


you add one line creating a list of slots like this:

class MyClass:
__slots__ = ['myVar1', 'myVar2', 'myVar3']
def __init__(self, var1, var2, var3):
self.myVar1 = var1
self.myVar2 = var2
self.myVar3 = var3

and you get a bit of a speed up!

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home