際際滷

際際滷Share a Scribd company logo
Memory Handling
&
Garbage Collection in Python
Prepared by:
Ms. Pooja Mehta
ITSNS Branch,
GTU-CDAC-BISAG ME Program,
Gandhinagar
1
Memory Management
3 March 2016By: Pooja Mehta
2
 The process of binding values to memory
locations
 Whether done automatically (as in
Python), or partially by the programmer
(as in C/C++), dynamic memory
management is an important part of
programming language design.
Three Categories of Memory
(for Data Storage)
3 March 2016By: Pooja Mehta
3
 Static: storage requirements are known
prior to run time; lifetime is the entire
program execution
 Run-time stack: memory associated with
active functions
Structured as stack frames
 Heap: dynamically allocated storage; the
least organized and most dynamic storage
area
Cont..
3 March 2016By: Pooja Mehta
4
Cont..
3 March 2016By: Pooja Mehta
5
Memory Leaks and Garbage
Collection
3 March 2016By: Pooja Mehta
6
 Three types of storage
 Static
 Stack
 Heap
 Problems with heap storage:
 Memory leaks (garbage): failure to free storage when
pointers (references) are reassigned
 Dangling pointers: when storage is freed, but
references to the storage still exist.
Garbage
3 March 2016By: Pooja Mehta
7
 Any block of heap memory that cannot be
accessed by the program; i.e., there is no
stack pointer to the block; but which the
runtime system thinks is in use.
 Garbage is created in several ways:
 A function ends without returning the space
allocated to a local array or other dynamic
variable.
 A node is deleted from a linked data structure, but
isnt freed
Garbage Collection
3 March 2016By: Pooja Mehta
8
 All inaccessible blocks of storage are identified
and returned to the free list.
 The heap may also be compacted at this time:
allocated space is compressed into one end of
the heap, leaving all free space in a large
block at the other end.
Implementing Automated
Garbage Collection
3 March 2016By: Pooja Mehta
9
 If programmers were perfect, garbage
collection wouldnt be needed.
 There are three major approaches to
automating the process:
 Reference counting
 Mark-sweep
 Copy collection
Reference Counting
10
 Prior to Python version 2.0, the Python
interpreter only used reference counting for
memory management.
 Reference counting works by counting the
number of times an object is referenced by
other objects in the system.
 When references to an object are removed,
the reference count for an object is
decremented.
 When the reference count becomes zero the
object is de allocated.
3 March 2016By: Pooja Mehta
Mark and Sweep
3 March 2016By: Pooja Mehta
11
 Reference counting tries to find unreachable
objects by finding objects with no incoming
references.
 Imprecise because we forget which references
those are.
Cont..
3 March 2016By: Pooja Mehta
12
 The root set is the set of memory locations in
the program that are known to be reachable.
 Any objects reachable from the root set are
reachable.
 Any objects not reachable from the root set are
not reachable.
Cont..
3 March 2016By: Pooja Mehta
13
Marking phase: Find reachable objects.
 Add the root set to a worklist.
 While the worklist isn't empty:
 Remove an object from the worklist.
 If it is not marked, mark it and add to the worklist all
objects reachable from that object.
Sweeping phase: Reclaim free memory.
 For each allocated object:
 If that object isn't marked, reclaim its memory.
 If the object is marked, unmark it (so on the next
mark-and sweep iteration we have to mark it again).
Copy Collection
3 March 2016By: Pooja Mehta
14
 Divide heap into two semispaces.
 Allocate from one space (fromspace) till full.
 Copy live data into other space (tospace).
 Switch roles of the spaces.
 Requires fixing pointers to moved data
(forwarding).
 Eliminates fragmentation.
 DFS improves locality, while BFS does not
require any extra storage.
References
15
 https://docs.python.org/2/c-api/memory.html
 http://foobarnbaz.com/2012/07/08/understanding-
python-variables/
 https://www.digi.com/wiki/developer/index.php/Pyt
hon_Garbage_Collection
3 March 2016By: Pooja Mehta
16
Thank
you...!

More Related Content

Viewers also liked (19)

No-no-no approach
No-no-no approachNo-no-no approach
No-no-no approach
Timofey Golovin
GALNT11 as a new molecular marker in chronic lymphocytic leukemia
GALNT11 as a new molecular marker in chronic lymphocytic leukemiaGALNT11 as a new molecular marker in chronic lymphocytic leukemia
GALNT11 as a new molecular marker in chronic lymphocytic leukemia
Diana Agudelo
Kossuth Palo Alto Economic Development Crop Jan-June Newsletter
Kossuth Palo Alto Economic Development Crop Jan-June NewsletterKossuth Palo Alto Economic Development Crop Jan-June Newsletter
Kossuth Palo Alto Economic Development Crop Jan-June Newsletter
Mid Iowa Growth Partnership
MUN U.K.
MUN U.K.MUN U.K.
MUN U.K.
anatfurber
BACTERIAL INFECTION AND IMMUNE SYSTEM RESPONSE
BACTERIAL INFECTION AND IMMUNE SYSTEM RESPONSEBACTERIAL INFECTION AND IMMUNE SYSTEM RESPONSE
BACTERIAL INFECTION AND IMMUNE SYSTEM RESPONSE
Diana Agudelo
GWC14: Toby Beresford - "Zoopla Gravity: Orbit strategy"
GWC14: Toby Beresford - "Zoopla Gravity: Orbit strategy"GWC14: Toby Beresford - "Zoopla Gravity: Orbit strategy"
GWC14: Toby Beresford - "Zoopla Gravity: Orbit strategy"
gamificationworldcongress
GWC14: Carlos Guardiola - "Who gamifies the gamificators?
GWC14: Carlos Guardiola - "Who gamifies the gamificators?GWC14: Carlos Guardiola - "Who gamifies the gamificators?
GWC14: Carlos Guardiola - "Who gamifies the gamificators?
gamificationworldcongress
Presentasjon om biler
Presentasjon om bilerPresentasjon om biler
Presentasjon om biler
Abdelhay1961
GWC14: Robert Figueras - "Panzer Chocolate: Play the film!"
GWC14: Robert Figueras - "Panzer Chocolate: Play the film!"GWC14: Robert Figueras - "Panzer Chocolate: Play the film!"
GWC14: Robert Figueras - "Panzer Chocolate: Play the film!"
gamificationworldcongress
Function points and elements
Function points and elementsFunction points and elements
Function points and elements
Busi Sreedhaar Reddy
GWC14: Isidro Rodrigo - "The boardgames that HR people [should] play"
GWC14: Isidro Rodrigo - "The boardgames that HR people [should] play"GWC14: Isidro Rodrigo - "The boardgames that HR people [should] play"
GWC14: Isidro Rodrigo - "The boardgames that HR people [should] play"
gamificationworldcongress
Days remembered
Days rememberedDays remembered
Days remembered
The Baltimore Sun
Katharina reiss
Katharina reissKatharina reiss
Katharina reiss
nameless422
Fgd medan
Fgd medanFgd medan
Fgd medan
Ardi Novra
19 Feb 2011 ZGM
19 Feb 2011 ZGM19 Feb 2011 ZGM
19 Feb 2011 ZGM
Alan Ralston
Elao integral presentation
Elao integral presentationElao integral presentation
Elao integral presentation
ElenaSoto75
Tugas agama
Tugas agamaTugas agama
Tugas agama
Syarif Utsman
2011 Fort Dodge & Webster County Iowa Laborshed Summary
2011 Fort Dodge & Webster County Iowa Laborshed Summary2011 Fort Dodge & Webster County Iowa Laborshed Summary
2011 Fort Dodge & Webster County Iowa Laborshed Summary
Mid Iowa Growth Partnership
Presentasjon om biler2
Presentasjon om biler2Presentasjon om biler2
Presentasjon om biler2
Abdelhay1961
GALNT11 as a new molecular marker in chronic lymphocytic leukemia
GALNT11 as a new molecular marker in chronic lymphocytic leukemiaGALNT11 as a new molecular marker in chronic lymphocytic leukemia
GALNT11 as a new molecular marker in chronic lymphocytic leukemia
Diana Agudelo
Kossuth Palo Alto Economic Development Crop Jan-June Newsletter
Kossuth Palo Alto Economic Development Crop Jan-June NewsletterKossuth Palo Alto Economic Development Crop Jan-June Newsletter
Kossuth Palo Alto Economic Development Crop Jan-June Newsletter
Mid Iowa Growth Partnership
BACTERIAL INFECTION AND IMMUNE SYSTEM RESPONSE
BACTERIAL INFECTION AND IMMUNE SYSTEM RESPONSEBACTERIAL INFECTION AND IMMUNE SYSTEM RESPONSE
BACTERIAL INFECTION AND IMMUNE SYSTEM RESPONSE
Diana Agudelo
GWC14: Toby Beresford - "Zoopla Gravity: Orbit strategy"
GWC14: Toby Beresford - "Zoopla Gravity: Orbit strategy"GWC14: Toby Beresford - "Zoopla Gravity: Orbit strategy"
GWC14: Toby Beresford - "Zoopla Gravity: Orbit strategy"
gamificationworldcongress
GWC14: Carlos Guardiola - "Who gamifies the gamificators?
GWC14: Carlos Guardiola - "Who gamifies the gamificators?GWC14: Carlos Guardiola - "Who gamifies the gamificators?
GWC14: Carlos Guardiola - "Who gamifies the gamificators?
gamificationworldcongress
Presentasjon om biler
Presentasjon om bilerPresentasjon om biler
Presentasjon om biler
Abdelhay1961
GWC14: Robert Figueras - "Panzer Chocolate: Play the film!"
GWC14: Robert Figueras - "Panzer Chocolate: Play the film!"GWC14: Robert Figueras - "Panzer Chocolate: Play the film!"
GWC14: Robert Figueras - "Panzer Chocolate: Play the film!"
gamificationworldcongress
GWC14: Isidro Rodrigo - "The boardgames that HR people [should] play"
GWC14: Isidro Rodrigo - "The boardgames that HR people [should] play"GWC14: Isidro Rodrigo - "The boardgames that HR people [should] play"
GWC14: Isidro Rodrigo - "The boardgames that HR people [should] play"
gamificationworldcongress
Katharina reiss
Katharina reissKatharina reiss
Katharina reiss
nameless422
19 Feb 2011 ZGM
19 Feb 2011 ZGM19 Feb 2011 ZGM
19 Feb 2011 ZGM
Alan Ralston
Elao integral presentation
Elao integral presentationElao integral presentation
Elao integral presentation
ElenaSoto75
2011 Fort Dodge & Webster County Iowa Laborshed Summary
2011 Fort Dodge & Webster County Iowa Laborshed Summary2011 Fort Dodge & Webster County Iowa Laborshed Summary
2011 Fort Dodge & Webster County Iowa Laborshed Summary
Mid Iowa Growth Partnership
Presentasjon om biler2
Presentasjon om biler2Presentasjon om biler2
Presentasjon om biler2
Abdelhay1961

More from POOJA MEHTA (7)

Data Validation for Business Continuity Planning
Data Validation for Business Continuity PlanningData Validation for Business Continuity Planning
Data Validation for Business Continuity Planning
POOJA MEHTA
Otp authentication scheme based on ECC
Otp authentication scheme based on ECCOtp authentication scheme based on ECC
Otp authentication scheme based on ECC
POOJA MEHTA
Fault tolerance in Big Data
Fault tolerance in Big DataFault tolerance in Big Data
Fault tolerance in Big Data
POOJA MEHTA
Computer organization and architecture
Computer organization and architectureComputer organization and architecture
Computer organization and architecture
POOJA MEHTA
The optimization and implementation of iptables rules set
The optimization and implementation of iptables rules setThe optimization and implementation of iptables rules set
The optimization and implementation of iptables rules set
POOJA MEHTA
Deadlock Detection
Deadlock DetectionDeadlock Detection
Deadlock Detection
POOJA MEHTA
Network Data Representation
Network Data RepresentationNetwork Data Representation
Network Data Representation
POOJA MEHTA
Data Validation for Business Continuity Planning
Data Validation for Business Continuity PlanningData Validation for Business Continuity Planning
Data Validation for Business Continuity Planning
POOJA MEHTA
Otp authentication scheme based on ECC
Otp authentication scheme based on ECCOtp authentication scheme based on ECC
Otp authentication scheme based on ECC
POOJA MEHTA
Fault tolerance in Big Data
Fault tolerance in Big DataFault tolerance in Big Data
Fault tolerance in Big Data
POOJA MEHTA
Computer organization and architecture
Computer organization and architectureComputer organization and architecture
Computer organization and architecture
POOJA MEHTA
The optimization and implementation of iptables rules set
The optimization and implementation of iptables rules setThe optimization and implementation of iptables rules set
The optimization and implementation of iptables rules set
POOJA MEHTA
Deadlock Detection
Deadlock DetectionDeadlock Detection
Deadlock Detection
POOJA MEHTA
Network Data Representation
Network Data RepresentationNetwork Data Representation
Network Data Representation
POOJA MEHTA

Recently uploaded (20)

Data recovery and Digital evidence controls in digital frensics.pdf
Data recovery and Digital evidence controls in digital frensics.pdfData recovery and Digital evidence controls in digital frensics.pdf
Data recovery and Digital evidence controls in digital frensics.pdf
Abhijit Bodhe
INVESTIGATION OF PUEA IN COGNITIVE RADIO NETWORKS USING ENERGY DETECTION IN D...
INVESTIGATION OF PUEA IN COGNITIVE RADIO NETWORKS USING ENERGY DETECTION IN D...INVESTIGATION OF PUEA IN COGNITIVE RADIO NETWORKS USING ENERGY DETECTION IN D...
INVESTIGATION OF PUEA IN COGNITIVE RADIO NETWORKS USING ENERGY DETECTION IN D...
csijjournal
Environmental Product Declaration - Uni Bell
Environmental Product Declaration - Uni BellEnvironmental Product Declaration - Uni Bell
Environmental Product Declaration - Uni Bell
ManishPatel169454
Air pollution is contamination of the indoor or outdoor environment by any ch...
Air pollution is contamination of the indoor or outdoor environment by any ch...Air pollution is contamination of the indoor or outdoor environment by any ch...
Air pollution is contamination of the indoor or outdoor environment by any ch...
dhanashree78
惠悋惡 悋惠悋惶 悋悋愆悋悧 愆悛惠 悋悽惘愕悋悸
惠悋惡 悋惠悋惶 悋悋愆悋悧 愆悛惠 悋悽惘愕悋悸惠悋惡 悋惠悋惶 悋悋愆悋悧 愆悛惠 悋悽惘愕悋悸
惠悋惡 悋惠悋惶 悋悋愆悋悧 愆悛惠 悋悽惘愕悋悸
o774656624
AI ppt on water jug problem by shivam sharma
AI ppt on water jug problem by shivam sharmaAI ppt on water jug problem by shivam sharma
AI ppt on water jug problem by shivam sharma
ShivamSharma588604
Biases, our brain and software development
Biases, our brain and software developmentBiases, our brain and software development
Biases, our brain and software development
Matias Iacono
eng funda notes.pdfddddddddddddddddddddddd
eng funda notes.pdfdddddddddddddddddddddddeng funda notes.pdfddddddddddddddddddddddd
eng funda notes.pdfddddddddddddddddddddddd
aayushkumarsinghec22
Von karman Equation full derivation .pdf
Von karman Equation full derivation  .pdfVon karman Equation full derivation  .pdf
Von karman Equation full derivation .pdf
Er. Gurmeet Singh
US Patented ReGenX Generator, ReGen-X Quatum Motor EV Regenerative Accelerati...
US Patented ReGenX Generator, ReGen-X Quatum Motor EV Regenerative Accelerati...US Patented ReGenX Generator, ReGen-X Quatum Motor EV Regenerative Accelerati...
US Patented ReGenX Generator, ReGen-X Quatum Motor EV Regenerative Accelerati...
Thane Heins NOBEL PRIZE WINNING ENERGY RESEARCHER
Sppu engineering artificial intelligence and data science semester 6th Artif...
Sppu engineering  artificial intelligence and data science semester 6th Artif...Sppu engineering  artificial intelligence and data science semester 6th Artif...
Sppu engineering artificial intelligence and data science semester 6th Artif...
pawaletrupti434
Helium Boosting & Decanting With Hydro Test Machine
Helium Boosting & Decanting With Hydro Test MachineHelium Boosting & Decanting With Hydro Test Machine
Helium Boosting & Decanting With Hydro Test Machine
Paskals Fluid Systems Pvt. Ltd.
only history of java.pptx real bihind the name java
only history of java.pptx real bihind the name javaonly history of java.pptx real bihind the name java
only history of java.pptx real bihind the name java
mushtaqsaliq9
Design of cannal by Kennedy Theory full problem solved
Design of cannal by Kennedy Theory full problem solvedDesign of cannal by Kennedy Theory full problem solved
Design of cannal by Kennedy Theory full problem solved
Er. Gurmeet Singh
Soil Properties and Methods of Determination
Soil Properties and  Methods of DeterminationSoil Properties and  Methods of Determination
Soil Properties and Methods of Determination
Rajani Vyawahare
Designing Flex and Rigid-Flex PCBs to Prevent Failure
Designing Flex and Rigid-Flex PCBs to Prevent FailureDesigning Flex and Rigid-Flex PCBs to Prevent Failure
Designing Flex and Rigid-Flex PCBs to Prevent Failure
Epec Engineered Technologies
Common Network Architecture:X.25 Networks, Ethernet (Standard and Fast): fram...
Common Network Architecture:X.25 Networks, Ethernet (Standard and Fast): fram...Common Network Architecture:X.25 Networks, Ethernet (Standard and Fast): fram...
Common Network Architecture:X.25 Networks, Ethernet (Standard and Fast): fram...
SnehPrasad2
health safety and environment presentation
health safety and environment presentationhealth safety and environment presentation
health safety and environment presentation
ssuserc606c7
Design and Analysis of Algorithms Unit 5
Design and Analysis of Algorithms Unit 5Design and Analysis of Algorithms Unit 5
Design and Analysis of Algorithms Unit 5
sureshkumara29
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
prasadmutkule1
Data recovery and Digital evidence controls in digital frensics.pdf
Data recovery and Digital evidence controls in digital frensics.pdfData recovery and Digital evidence controls in digital frensics.pdf
Data recovery and Digital evidence controls in digital frensics.pdf
Abhijit Bodhe
INVESTIGATION OF PUEA IN COGNITIVE RADIO NETWORKS USING ENERGY DETECTION IN D...
INVESTIGATION OF PUEA IN COGNITIVE RADIO NETWORKS USING ENERGY DETECTION IN D...INVESTIGATION OF PUEA IN COGNITIVE RADIO NETWORKS USING ENERGY DETECTION IN D...
INVESTIGATION OF PUEA IN COGNITIVE RADIO NETWORKS USING ENERGY DETECTION IN D...
csijjournal
Environmental Product Declaration - Uni Bell
Environmental Product Declaration - Uni BellEnvironmental Product Declaration - Uni Bell
Environmental Product Declaration - Uni Bell
ManishPatel169454
Air pollution is contamination of the indoor or outdoor environment by any ch...
Air pollution is contamination of the indoor or outdoor environment by any ch...Air pollution is contamination of the indoor or outdoor environment by any ch...
Air pollution is contamination of the indoor or outdoor environment by any ch...
dhanashree78
惠悋惡 悋惠悋惶 悋悋愆悋悧 愆悛惠 悋悽惘愕悋悸
惠悋惡 悋惠悋惶 悋悋愆悋悧 愆悛惠 悋悽惘愕悋悸惠悋惡 悋惠悋惶 悋悋愆悋悧 愆悛惠 悋悽惘愕悋悸
惠悋惡 悋惠悋惶 悋悋愆悋悧 愆悛惠 悋悽惘愕悋悸
o774656624
AI ppt on water jug problem by shivam sharma
AI ppt on water jug problem by shivam sharmaAI ppt on water jug problem by shivam sharma
AI ppt on water jug problem by shivam sharma
ShivamSharma588604
Biases, our brain and software development
Biases, our brain and software developmentBiases, our brain and software development
Biases, our brain and software development
Matias Iacono
eng funda notes.pdfddddddddddddddddddddddd
eng funda notes.pdfdddddddddddddddddddddddeng funda notes.pdfddddddddddddddddddddddd
eng funda notes.pdfddddddddddddddddddddddd
aayushkumarsinghec22
Von karman Equation full derivation .pdf
Von karman Equation full derivation  .pdfVon karman Equation full derivation  .pdf
Von karman Equation full derivation .pdf
Er. Gurmeet Singh
Sppu engineering artificial intelligence and data science semester 6th Artif...
Sppu engineering  artificial intelligence and data science semester 6th Artif...Sppu engineering  artificial intelligence and data science semester 6th Artif...
Sppu engineering artificial intelligence and data science semester 6th Artif...
pawaletrupti434
only history of java.pptx real bihind the name java
only history of java.pptx real bihind the name javaonly history of java.pptx real bihind the name java
only history of java.pptx real bihind the name java
mushtaqsaliq9
Design of cannal by Kennedy Theory full problem solved
Design of cannal by Kennedy Theory full problem solvedDesign of cannal by Kennedy Theory full problem solved
Design of cannal by Kennedy Theory full problem solved
Er. Gurmeet Singh
Soil Properties and Methods of Determination
Soil Properties and  Methods of DeterminationSoil Properties and  Methods of Determination
Soil Properties and Methods of Determination
Rajani Vyawahare
Designing Flex and Rigid-Flex PCBs to Prevent Failure
Designing Flex and Rigid-Flex PCBs to Prevent FailureDesigning Flex and Rigid-Flex PCBs to Prevent Failure
Designing Flex and Rigid-Flex PCBs to Prevent Failure
Epec Engineered Technologies
Common Network Architecture:X.25 Networks, Ethernet (Standard and Fast): fram...
Common Network Architecture:X.25 Networks, Ethernet (Standard and Fast): fram...Common Network Architecture:X.25 Networks, Ethernet (Standard and Fast): fram...
Common Network Architecture:X.25 Networks, Ethernet (Standard and Fast): fram...
SnehPrasad2
health safety and environment presentation
health safety and environment presentationhealth safety and environment presentation
health safety and environment presentation
ssuserc606c7
Design and Analysis of Algorithms Unit 5
Design and Analysis of Algorithms Unit 5Design and Analysis of Algorithms Unit 5
Design and Analysis of Algorithms Unit 5
sureshkumara29
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
prasadmutkule1

Memory Handling and Garbage Collection in Python

  • 1. Memory Handling & Garbage Collection in Python Prepared by: Ms. Pooja Mehta ITSNS Branch, GTU-CDAC-BISAG ME Program, Gandhinagar 1
  • 2. Memory Management 3 March 2016By: Pooja Mehta 2 The process of binding values to memory locations Whether done automatically (as in Python), or partially by the programmer (as in C/C++), dynamic memory management is an important part of programming language design.
  • 3. Three Categories of Memory (for Data Storage) 3 March 2016By: Pooja Mehta 3 Static: storage requirements are known prior to run time; lifetime is the entire program execution Run-time stack: memory associated with active functions Structured as stack frames Heap: dynamically allocated storage; the least organized and most dynamic storage area
  • 4. Cont.. 3 March 2016By: Pooja Mehta 4
  • 5. Cont.. 3 March 2016By: Pooja Mehta 5
  • 6. Memory Leaks and Garbage Collection 3 March 2016By: Pooja Mehta 6 Three types of storage Static Stack Heap Problems with heap storage: Memory leaks (garbage): failure to free storage when pointers (references) are reassigned Dangling pointers: when storage is freed, but references to the storage still exist.
  • 7. Garbage 3 March 2016By: Pooja Mehta 7 Any block of heap memory that cannot be accessed by the program; i.e., there is no stack pointer to the block; but which the runtime system thinks is in use. Garbage is created in several ways: A function ends without returning the space allocated to a local array or other dynamic variable. A node is deleted from a linked data structure, but isnt freed
  • 8. Garbage Collection 3 March 2016By: Pooja Mehta 8 All inaccessible blocks of storage are identified and returned to the free list. The heap may also be compacted at this time: allocated space is compressed into one end of the heap, leaving all free space in a large block at the other end.
  • 9. Implementing Automated Garbage Collection 3 March 2016By: Pooja Mehta 9 If programmers were perfect, garbage collection wouldnt be needed. There are three major approaches to automating the process: Reference counting Mark-sweep Copy collection
  • 10. Reference Counting 10 Prior to Python version 2.0, the Python interpreter only used reference counting for memory management. Reference counting works by counting the number of times an object is referenced by other objects in the system. When references to an object are removed, the reference count for an object is decremented. When the reference count becomes zero the object is de allocated. 3 March 2016By: Pooja Mehta
  • 11. Mark and Sweep 3 March 2016By: Pooja Mehta 11 Reference counting tries to find unreachable objects by finding objects with no incoming references. Imprecise because we forget which references those are.
  • 12. Cont.. 3 March 2016By: Pooja Mehta 12 The root set is the set of memory locations in the program that are known to be reachable. Any objects reachable from the root set are reachable. Any objects not reachable from the root set are not reachable.
  • 13. Cont.. 3 March 2016By: Pooja Mehta 13 Marking phase: Find reachable objects. Add the root set to a worklist. While the worklist isn't empty: Remove an object from the worklist. If it is not marked, mark it and add to the worklist all objects reachable from that object. Sweeping phase: Reclaim free memory. For each allocated object: If that object isn't marked, reclaim its memory. If the object is marked, unmark it (so on the next mark-and sweep iteration we have to mark it again).
  • 14. Copy Collection 3 March 2016By: Pooja Mehta 14 Divide heap into two semispaces. Allocate from one space (fromspace) till full. Copy live data into other space (tospace). Switch roles of the spaces. Requires fixing pointers to moved data (forwarding). Eliminates fragmentation. DFS improves locality, while BFS does not require any extra storage.
  • 15. References 15 https://docs.python.org/2/c-api/memory.html http://foobarnbaz.com/2012/07/08/understanding- python-variables/ https://www.digi.com/wiki/developer/index.php/Pyt hon_Garbage_Collection 3 March 2016By: Pooja Mehta

Editor's Notes

  • #11: The user does not have to preallocate or deallocate memory by hand as one has to when using dynamic memory allocation in languages such as C or C++.
  • #12: The easiest way to create a reference cycle is to create an object which refers to itself as in the example below: def make_cycle(): l = [ ] l.append(l) make_cycle() Reference counting is extremely efficient but it does have some caveats. One such caveat is that it cannot handle reference cycles. A reference cycle is when there is no way to reach an object but its reference count is still greater than zero.
  • #14: Problems Memory Fragmentation Work proportional to size of heap Potential lack of locality of reference for newly allocated objects (fragmentation) Solution Compaction Contiguous live objects, contiguous free space
  • #15: Automatic Garbage Collection of Cycles Because reference cycles are take computational work to discover, garbage collection must be a scheduled activity. Python schedules garbage collection based upon a threshold of object allocations and object deallocations. When the number of allocations minus the number of deallocations are greater than the threshold number, the garbage collector is run. One can inspect the threshold for new objects (objects in Python known as generation 0 objects) by loading the gc module and asking for garbage collection thresholds. Because make_cycle() creates an object l which refers to itself, the object l will not automatically be freed when the function returns. This will cause the memory that l is using to be held onto until the Python garbage collector is invoked