3. Motivation
Managing memory manually is hard.
Who owns the memory?
Should I free these resources?
What happens with double frees?
Francisco Fernandez Castano (@fcofdezc) Python GC January 31, 2015 3 / 37
7. Basic concepts
Heap
A data structure in which objects may be allocated or deallocated in any
order.
Francisco Fernandez Castano (@fcofdezc) Python GC January 31, 2015 7 / 37
8. Basic concepts
Heap
A data structure in which objects may be allocated or deallocated in any
order.
Mutator
The part of a running program which executes application code.
Francisco Fernandez Castano (@fcofdezc) Python GC January 31, 2015 8 / 37
9. Basic concepts
Heap
A data structure in which objects may be allocated or deallocated in any
order.
Mutator
The part of a running program which executes application code.
Collector
The part of a running program responsible of garbage collection.
Francisco Fernandez Castano (@fcofdezc) Python GC January 31, 2015 9 / 37
10. Garbage collection
Definition
Garbage collection is automatic memory management. While the
mutator runs , it routinely allocates memory from the heap. If more
memory than available is needed, the collector reclaims unused memory
and returns it to the heap.
Francisco Fernandez Castano (@fcofdezc) Python GC January 31, 2015 10 / 37
11. CPython GC
CPython implementation has garbage collection.
CPython GC algorithm is Reference counting with cycle detector
It also has a generational GC.
Francisco Fernandez Castano (@fcofdezc) Python GC January 31, 2015 11 / 37
12. Young objects
[elem * 2 for elem in elements]
balance = (a / b / c) * 4
’asdadsasd -xxx’.replace(’x’, ’y’). replace(’a’, ’
foo.bar()
Francisco Fernandez Castano (@fcofdezc) Python GC January 31, 2015 12 / 37
29. Reference counting
Pros: Is incremental, as it works, it frees memory.
Cons: Detecting Cycles could be hard.
Cons: Size overhead on objects.
Francisco Fernandez Castano (@fcofdezc) Python GC January 31, 2015 29 / 37
31. Mark and Sweep Algorithm
Francisco Fernandez Castano (@fcofdezc) Python GC January 31, 2015 31 / 37
32. Mark and Sweep Algorithm
Francisco Fernandez Castano (@fcofdezc) Python GC January 31, 2015 32 / 37
33. Mark and Sweep Algorithm
Francisco Fernandez Castano (@fcofdezc) Python GC January 31, 2015 33 / 37
34. Mark and Sweep Algorithm
Francisco Fernandez Castano (@fcofdezc) Python GC January 31, 2015 34 / 37
35. Mark and sweep
Pros: Can collect cycles.
Cons: Basic implementation stops the world
Francisco Fernandez Castano (@fcofdezc) Python GC January 31, 2015 35 / 37