Skip to content
Advertisement

python: class vs tuple huge memory overhead (?)

I’m storing a lot of complex data in tuples/lists, but would prefer to use small wrapper classes to make the data structures easier to understand, e.g.

JavaScript

would be preferable over

JavaScript

however there seems to be a horrible memory overhead:

JavaScript

and

JavaScript

Why? is there any obvious alternative solution that I didn’t think of?

Thanks!

(I know, in this example the ‘wrapper’ class looks silly. But when the data becomes more complex and nested, it is more useful)

Advertisement

Answer

As others have said in their answers, you’ll have to generate different objects for the comparison to make sense.

So, let’s compare some approaches.

tuple

JavaScript

class Person

JavaScript

namedtuple (tuple + __slots__)

JavaScript

namedtuple is basically a class that extends tuple and uses __slots__ for all named fields, but it adds fields getters and some other helper methods (you can see the exact code generated if called with verbose=True).

class Person + __slots__

JavaScript

This is a trimmed-down version of namedtuple above. A clear winner, even better than pure tuples.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement