Senior LevelJavaScript & TypeScript
How does JavaScript garbage collection work (mark-and-sweep, generational GC)?
❓ Interview Prompt: Explain V8 garbage collection, young vs old generation, Scavenger algorithm, and Mark-Sweep-Compact.
V8 uses a generational garbage collector based on the Weak Generational Hypothesis: most objects die young.
Generations:
1
Young Generation (New Space):
•
1MB–8MB buffer for newly allocated objects.
•
Collected frequently using the fast Scavenger (Cheney's algorithm) algorithm.
•
Objects that survive 2 Scavenger cycles are promoted to Old Generation.
2
Old Generation (Old Space):
•
Stores long-lived objects.
•
Collected using Mark-Sweep-Compact:
•
Mark: Traverse root references and mark reachable objects.
•
Sweep: Reclaim memory of un-marked objects.
•
Compact: Defragment memory pages by moving live objects together.
Code Implementation Example
javascript
// Simulating short-lived vs long-lived allocation
function processBatch(items) {
// Short-lived: created inside loop, collected by Scavenger (Young Gen)
items.forEach(item => {
const temp = { id: item.id, formatted: item.name.toUpperCase() };
saveToDb(temp);
});
}
// Long-lived: persistent cache promoted to Old Generation
const globalCache = new Map();
function cacheUser(id, user) {
globalCache.set(id, user); // Survives multiple GC cycles -> Old Gen
}💡Demonstrating young generation ephemeral objects vs old generation long-lived cache.
🎯 Interview Key Takeaway
V8 optimizes GC by separating short-lived objects (Scavenger) from long-lived objects (Mark-Sweep-Compact).
#Garbage Collection#V8#Memory#Senior
Back to all JavaScript & TypeScript Questions→