Memory Optimization
Memory Optimization
Section titled “Memory Optimization”Introduction
Section titled “Introduction”Memory optimization is critical for performance, especially on mobile devices. Optimized memory usage means faster page loads, smoother animations, and better battery life.
Topics Covered
Section titled “Topics Covered”- Common Memory Leaks — Global variables, detached DOM, and closures
- Object Pooling — Reusing objects to reduce GC pressure
- Event Cleanup — Preventing listener leaks with proper teardown
Key Strategies
Section titled “Key Strategies”1. Avoid Global Variables
Section titled “1. Avoid Global Variables”// ❌ Leaks to global scopefunction bad() { data = 'leaked'; }
// ✅ Properly scopedfunction good() { let data = 'scoped'; }2. Object Pooling
Section titled “2. Object Pooling”// ❌ Creating new objects repeatedlyfunction createParticles(count) { const particles = []; for (let i = 0; i < count; i++) { particles.push({ x: 0, y: 0, vx: 0, vy: 0 }); } return particles;}
// ✅ Reusing objects (object pooling)const particlePool = [];function getParticle() { return particlePool.pop() || { x: 0, y: 0, vx: 0, vy: 0 };}function releaseParticle(p) { particlePool.push(p);}3. Limit Closures Holding Large Data
Section titled “3. Limit Closures Holding Large Data”// ❌ Closure holds large data foreverfunction processData() { const largeData = new Array(1000000); return function() { console.log('Still holds largeData'); };}
// ✅ Clear reference when no longer neededfunction processData() { const largeData = new Array(1000000); const result = computeResult(largeData); return function() { console.log(result); // Only holds result, not largeData };}4. Proper Event Cleanup
Section titled “4. Proper Event Cleanup”class Component { mount() { this.handler = () => { /* ... */ }; window.addEventListener('resize', this.handler); }
unmount() { window.removeEventListener('resize', this.handler); // ✅ }}Summary
Section titled “Summary”- Avoid global variables
- Use object pooling for frequently created objects
- Be careful with closures holding large data
- Always clean up event listeners
- Use WeakMap/WeakSet for object-associated metadata