rockstar - garbage collection Flashcards
What is garbage collection in C#?
- Automatic memory management process
- Identifies and reclaims memory that is no longer used by the program
Explain how garbage collection works in C#
- Garbage collector runs in background
- Identifies objects that are no longer reachable from the application’s root (local variables, static variables) and reclaims their memory
Garbage collection generations - Gen0
- Newly created objects
- Designed for short-lived objects that are expected to be collected quickly
- Objects in Gen0 are collected frequently
Garbage collection generations - Gen1
- Objects that survive Gen0 collection are promoted to Gen1
- These objects have longer lifespan than Gen0 but are still relatively short-lived
Garbage collection generations - Gen2
- Objects that survive multiple Gen1 collections are promoted to Gen2
- Long-lived objects
- Collections here are less frequent
Garbage collection process
Marking
Garbage collector identifies which objects can be cleaned and marks the live objects
Sweeping
Garbage collector reclaims the memory occupied by objects that are marked as live
Compacting
Objects that survive Gen0 are promoted to Gen1, etc.
What is the purpose of the System.GC class in C#?
- Provides methods and properties for interacting with garbage collector
- Allows developers to request garbage collection, etc.
What is the difference between managed and unmanaged resources in the context of garbage collection?
Managed resources
Objects under control of .NET runtime
Subject to garbage collection
Unmanaged resources
External resources such as database connections
Require explicit cleanup
How can you force garbage collection in C#?
- Calling the System.GC.Collect method
- Not recommended because it can disrupt the natural behavior of the garbage collector
What are memory leaks, and how can you avoid them in C#?
- Occurs when objects are not properly released
- Causing memory consumption to grow indefinitely
To avoid:
- ensure that objects are properly disposed of
- especially unmanaged resources by using IDisposable or the ‘using’ statement
Explain the concept of the “root” in garbage collection.
- Set of references that are directly accessible from the program
- Includes local variables, static variables, and references from active threads
What is the impact of garbage collection on application performance?
- Temporary pauses can occur called “garbage collection pauses”
What are weak references in C#, and when are they useful?
- They indicate objects that can be garbage collected even if they have references