Curriculum
Concept 92 // Module 10: JavaScript Engine, Memory, Performance & Security
Garbage Collection: Mark-and-Sweep & Generational GC
Module 10: JavaScript Engine, Memory, Performance & Security•Concept 92 of 100• 5 min read
Garbage Collection: Mark-and-Sweep & Generational GC
JavaScript manages memory automatically using **Garbage Collection (GC)**. The V8 engine implements a **Generational Garbage Collector** based on the hypothesis that most objects die young: splitting memory into **Young Generation (Scavenger)** and **Old Generation (Mark-Sweep-Compact)**.
The Core Concept
The Young Gen uses the fast 'Scavenge' algorithm copying surviving objects between Semi-spaces. Objects surviving multiple cycles are promoted to the Old Generation, which uses incremental Mark-Sweep-Compact.
Syntax Reference
// Reachability determines GC survival:
let user = { name: "Subhajit" }; // Heap object allocated (Reachable via 'user')
user = null; // Unreachable! Eligible for garbage collection.Live Interactive Studio
Once an object is no longer reachable from any GC Root (call stack, global object), its memory is freed.
JavaScript Editor
Loading...
Console Output
Waiting for output...
Key Code Patterns in Action
01
Reachability Graph & Discarding Data
function createUser() {
const profile = { id: 101, token: "xyz789" };
return { id: profile.id }; // Only returns 'id'
// 'profile' variable goes out of scope.
// The object { id: 101, token: "xyz789" } becomes unreachable and is collected!
}
const activeUser = createUser();Once an object is no longer reachable from any GC Root (call stack, global object), its memory is freed.
02
Circular References are Safely Handled
function createCycle() {
const a = {};
const b = {};
a.neighbor = b;
b.neighbor = a; // Circular reference!
return "Done";
}
createCycle();
// Even though 'a' and 'b' reference each other,
// neither is reachable from the Root. Modern Mark-and-Sweep collects both!Unlike legacy reference counting, Mark-and-Sweep easily handles cyclic references because it checks root reachability.
03
1. Core Usage: Garbage Collection
// Core syntax and usage for Garbage Collection: Mark-and-Sweep & Generational GC
const feature = 'garbage-collection-mark-and-sweep-generational-gc';
console.log('Concept 92:', feature);
console.log('Active:', true);Illustrates the fundamental invocation and syntax structure for Garbage Collection: Mark-and-Sweep & Generational GC.
04
2. Defensive Handling & Edge Case
// Edge-case defensive handling
function handleSafe(input) {
if (input === null || input === undefined) return 'safe-fallback';
return String(input).trim();
}
console.log(handleSafe('garbage-collection-mark-and-sweep-generational-gc'));
console.log(handleSafe(null));Shows how to write defensive, safe JavaScript code that handles nullish or unexpected inputs when working with Garbage Collection: Mark-and-Sweep & Generational GC.
05
3. Clean Architecture & Production Pattern
// Production-grade pattern for Garbage Collection: Mark-and-Sweep & Generational GC
const settings = Object.freeze({
id: 'garbage-collection-mark-and-sweep-generational-gc',
ready: true,
timestamp: Date.now()
});
console.log('Settings initialized:', settings.id, settings.ready);Demonstrates clean, immutable production code avoiding unintended state mutations.
Real-World Engineering Takeaways
Memory-Efficient Algorithms: Minimizing object allocations in render loops to prevent GC pauses.
Object Pooling: Reusing object instances in games to prevent scavenger thrashing.
Profiling RAM in DevTools: Using the Memory tab to analyze Heap Snapshots.
Under the Hood: Engine & Memory Mechanics
How JavaScript Executes This
The heap is divided into New Space (1-64MB) and Old Space (several GB). The Scavenger uses Cheney's copying algorithm; Old Space uses Tri-color marking (White, Grey, Black) incrementally.
Quick Knowledge Check
Test your understanding on these 10 questions (one by one):
Score: 0 / 10
Question 1 of 10 • Core Purpose & Mental Model
What is the core purpose of Garbage Collection: Mark-and-Sweep & Generational GC in JavaScript?
// Concept 92: Garbage Collection: Mark-and-Sweep & Generational GC
// Understanding the core mental model1 / 10