Python Memory Usage using __slots__

I have been trying to reduce memory usage on our application server, and experimented with using __slots__ to reduce memory usage.

The memory overhead of using __dict__ vs __slots__ turned out to be 147 bytes per object.

Here are my results

Test Total Memory Bytes per object
slots 40880K 41
dicts 183840K 188

Using the following test script

class C(object):
#__slots__ = ('abc', 'defg')
pass

a = []
for i in xrange(1000000):
c = C()
c.abc = 1
c.defg = 2
a.append(c)

That’s quite promising. Now, if I can make that work with our in-house ORM.

You should follow me on twitter here

4 Responses to “Python Memory Usage using __slots__”

  1. ulrik writes:

    The big question for me is *how do you measure memory consumption*?

  2. Chui writes:

    Good old Task Manager on Windows.

  3. John Eikenberry writes:

    Python-2.6 has a new method for determining the size of an object; sys.getsizeof()

  4. Chui writes:

    Thanks John. Know of any heap inspectors that doesn’t crash a Python process?

Leave a Reply