Python Memory Management and Tips Transcripts
Chapter: Python variables and memory
Lecture: Concept: Flyweight design pattern
Login or
purchase this course
to watch this video and the rest of the course contents.
0:00
Let's talk about a cool little optimization that Python uses for some of the objects that
0:05
are common and reused. Now you've heard me talk about the numbers,
0:08
and seeing small numbers behave differently than others.
0:11
And that's because Python applies what's called the flyweight design pattern to them.
0:16
So let me just read what Wikipedia had to say about it: "in computer programming,
0:19
flyweight is a software design pattern.
0:21
A flyweight is an object that minimizes memory usage by sharing as much data as
0:26
possible with other similar objects". So,
0:28
for example, numbers that have the same value could literally be the same place in
0:32
memory. Those are immutable. It is a way to use objects
0:36
in large numbers when a simple,
0:38
repeated representation would use an unacceptable amount of memory.
0:42
So, like if you have the number 3 appear 1000 times like that's gonna be
0:46
say, that would be 28k when really it could just be
0:50
28. So often some parts of the object state can be shared.
0:54
It's a common practice to hold them in external data structures and pass them to objects
0:58
temporarily when they're used. Okay,
1:00
so that's the flyweight design pattern,
1:03
and you'll see that python uses that some of the time,
1:05
especially around numbers.