Memory Allocation and Garbage Collection
You'll learn how to spot memory usage spikes and garbage collection pauses that can cause frame drops and UI freezes.
What Is Garbage Collection?
When JavaScript creates objects, arrays, or closures, the browser allocates memory for them. When those items are no longer needed, the garbage collector (GC) automatically reclaims that memory. Think of it like a janitor periodically cleaning up trash—but while the janitor works, everything else pauses.
Why This Matters for Performance
Garbage collection isn't free. When the browser runs GC, it often pauses JavaScript execution. If you're allocating and discarding lots of objects rapidly (like inside animation loops or event handlers), the GC has to run frequently. These pauses can:
- Drop frames below 60 FPS (causing jank)
- Freeze the UI temporarily
- Make interactions feel sluggish
Spotting Memory Issues in Performance Panel
The Performance panel shows:
- Memory allocation spikes (blue line going up)
- Garbage collection events (downward drops in the memory graph, often marked with small icons)
- Correlation with frame drops (when GC runs during animations)
If you see frequent GC pauses coinciding with dropped frames or long tasks, your code is likely creating too many temporary objects.
Common Causes
- Creating objects inside loops or frequently-called functions
- Rebuilding large arrays or DOM structures repeatedly
- Closures capturing large objects unintentionally
- Not reusing objects when possible
Key Takeaway: Monitor memory allocation patterns and GC pauses in the Performance panel to identify when excessive object creation is causing performance bottlenecks—reducing allocations keeps the janitor from interrupting your animations.