devork

E pur si muove

__slots__: worth the trouble?

Wednesday, May 30, 2007

I find __slots__ annoying. They seem to have a lot of rules about their use and make things like a borgs rather awkward to use (I even prefer to use a singleton instead of a borg in new-style classes because of this).

And all it does is safe some space in memory (AFAIK). Make me wonder if it's worth it. Google claims there are about 2k hits for __slots__. Compare to e.g. about 300k hits when doing the same search for __init__.

Maybe I'm just overreacting though. Maybe having all class data in one place is not that important. Or maybe there are just massive gains in using __slots__ for some people that do make it worth it. But I'm not one of them so hence my rant.

2 comments:

Douglas said...

The benefit of __slots__ is a decrease in memory and a dramatic increase in lookup speed. If you are going to have millions of light weight objects with just a few attributes, __slots__ can provide an order of magnitude speedup.

With that said, one of the things we ABUSE __slots__ with is to provide a system in which no attributes can be added to an object of a given class. This is not recommended and only a side affect. The only other way to do the same thing is to override __setattr__ which can get very, very complicated. __slots__ is just too simple to not use.

Joe said...

I've only had to use __slots__ once, but being able to was a life saver. We had millions of a particular object and the computer kept swapping then running out of memory. Using __slots__ for a particular class made the program easily fit into memory and let us complete the calculations.

I haven't needed it since but being able to reduce memory consumption when needed is very handy.

New comments are not allowed.

Subscribe to: Post Comments (Atom)