Optimization of Data Classes
00:00 Optimizing data classes. In this section of the course, you’re going to take a look at slots, which can be used to make classes faster and take up less memory.
00:11 Data classes have no explicit syntax for working with slots, but the normal way of creating them works for data classes as well. You probably expect this as, after all, data classes are really just regular classes.
In essence, slots are defined using the
.__slots__ to list the variables on a class. Variables or attributes not present in the
.__slots__ list may not be defined. Furthermore, a slots class may not have default values.
01:16 The benefit of adding such restrictions is that optimizations can be performed. For instance, slots classes take up less memory, as can be measured using Pympler.
Similarly, slots classes are typically faster to work with. The following example measures the speed of attribute access on a slots data class and a regular data class using
timeit from the standard library.
03:04 In this particular example, the slot class is about 20% faster. So now that you’ve learned a great deal about data classes, let’s sum up everything that you’ve covered.
Become a Member to join the conversation.