Generational GC
- Node.js course
- Expert
- Lesson 20/47
- 5 min
Learn generational GC and Scavenge.
Generational GC
Generational garbage collection splits objects by age into two generations: young and old. New objects start in the young generation; those that survive a few collection cycles are promoted to the old generation. The young generation is collected often, the old one rarely.
A shouldPromote(survivalCount) function models the promotion decision: it returns true when the survival count is 2 or more. Example: shouldPromote(1) is false, shouldPromote(3) is true. This explains with a simple threshold when V8 moves an object from young to old. Real V8 thresholds are more complex but the idea is the same: frequently surviving objects promote into the rarely collected old generation. This reduces garbage collection cost.
The survival count
An object's survival count tells how many garbage collection cycles it has outlived. Each cycle a surviving object's count increases; once past the threshold it promotes to the old generation. This keeps hot data out of the fast-collected young generation.
Example: shouldPromote(1) returns false; the object is still young. shouldPromote(3) returns true; the object promotes to old. This model shows the core logic of generational GC with a simple comparison: survivalCount >= 2. In the old generation objects live longer and are collected less often; this boosts overall GC efficiency. Most objects die young; that is why young collection is fast.
Practice Write the promotion function
Write function shouldPromote(survivalCount). Return survivalCount >= 2. Print console.log(shouldPromote(1)) and console.log(shouldPromote(3)).
Starter code
// Write a shouldPromote function
// Return true if survival count is 2 or more
// Print two calls (1 and 3)
// write hereSample solution
function shouldPromote(survivalCount) {
return survivalCount >= 2;
}
console.log(shouldPromote(1));
console.log(shouldPromote(3));Expected output
false true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the promotion threshold
return survivalCount >= ____;
return survivalCount >= 2;
Explanation: 2 or more survivals promote.
2 Match each concept to its description
| Term | Meaning |
|---|---|
Young generation |
New objects |
Old generation |
Surviving objects |
Survival count |
Number of survivals |
shouldPromote |
Promotion decision |
3 What does shouldPromote(1) return (threshold 2)?
function shouldPromote(s) { return s >= 2; }
shouldPromote(1)- true
- 2
- 1
- false Correct answer
Explanation: 1 < 2 so it returns false.