Lesson 27/30

Tutorials C# Mastery

Garbage Collection Segments & LOH Internals

On this page

Garbage Collection Internals

The Garbage Collector (GC) is the guardian of your application's memory. While it is automatic, a Senior Architect must understand how it organizes data to avoid the dreaded "Stop-the-World" pauses that can make a professional application feel laggy.

1. The Three Generations

The GC assumes: "The newer an object is, the more likely it is to die quickly."

  • Gen 0: For short-lived objects (temporary variables). Cleaned up instantly and very frequently.
  • Gen 1: A buffer area for objects that survived Gen 0.
  • Gen 2: For long-lived objects (static data, caches, singletons). Collections here are very expensive and "Stop the World."

2. The LOH (Large Object Heap)

Any object larger than 85,000 bytes (like a large array) bypasses Gen 0 and goes directly to the Large Object Heap. The LOH is never compacted by the GC by default, which can lead to Memory Fragmentation where you have plenty of total RAM but no single continuous block large enough for a new object.

3. The Finalizer Queue

Objects that implement Finalizers (the ~ClassName syntax) cannot be deleted in one pass. The GC has to move them to a special queue, run the finalizer on a separate thread, and then delete them in the *next* GC cycle. This is why you should always prefer IDisposable.

4. Interview Mastery

Q: "What is a 'Memory Leak' in a managed language like C# if we have an automatic Garbage Collector?"

Architect Answer: "A memory leak in C# almost always occurs through 'Lingering References.' The GC only deletes objects if they are unreachable. If you add a temporary object to a static list or subscribe to a long-lived event without unsubscribing, the 'Root' (the static list) keeps a pointer to the object. The GC sees a valid path to the object and refuses to delete it. Over time, your RAM usage climbs until the server crashes. The most common leaks are caused by unclosed Event Subscriptions, Static Dictionaries, and Captive Dependencies in DI."

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

C# Mastery
Course syllabus
1. Modern C# & Framework Fundamentals
2. Control Flow & Logical Structures
3. Object-Oriented Mastery
4. Functional C# & Collections
5. Asynchronous & Parallel Programming
6. Advanced Engineering & High Performance
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details