Python 3, an illustrated tour Transcripts
Chapter: Classes and inheritance
Lecture: Dictionary Key Sharing
0:01 In this video, I want to introduce an optimization
0:03 that was brought to pass in pep 412 Python 3.3.
0:08 This is called key sharing dictionaries
0:10 and it's a nice little optimization
0:12 that will save memory when you're using Python 3.
0:15 From the pep we read: key sharing allows dictionaries,
0:18 which are used as attribute dictionaries
0:21 or the __dict__ attribute of an object
0:24 to share keys with other attribute dictionaries of instances of the same class.
0:28 So let's just understand what that means.
0:31 Basically whenever you create a class in Python
0:34 underneath the class there will be a __dict__ attribute
0:39 which will store the attribute names and map them to the values there.
0:43 What happens is if you're creating a bunch instances of classes
0:46 that have a bunch of attributes, these attributes are typically strings
0:50 and those strings will be repeated and so Python the interpreter
0:53 would go out and create a new string for each attribute
0:57 and those strings could add up if you're creating thousands
1:01 or many more instances of a class.
1:04 So this is a nice little optimization,
1:07 what it does is it caches essentially the keys in a dictionary.
1:11 We also read from the pep that as a result of this optimization
1:14 these dictionaries are typically half the size of the current dictionary implementation.
1:18 Benchmarking shows that memory use is reduced
1:21 by 10 to 20 percent for object-oriented programs
1:24 with no significant change in memory use for other programs.
1:28 So you don't have to do anything about this
1:30 you get to take advantage of this automatically.
1:32 Also note that this optimization does not apply to dictionaries
1:37 only to the __dict__ dictionary in an instance.