Skip to content

Memory Optimization

Memory optimization is critical for performance, especially on mobile devices. Optimized memory usage means faster page loads, smoother animations, and better battery life.

// ❌ Leaks to global scope
function bad() { data = 'leaked'; }
// ✅ Properly scoped
function good() { let data = 'scoped'; }
// ❌ Creating new objects repeatedly
function 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);
}
// ❌ Closure holds large data forever
function processData() {
const largeData = new Array(1000000);
return function() {
console.log('Still holds largeData');
};
}
// ✅ Clear reference when no longer needed
function processData() {
const largeData = new Array(1000000);
const result = computeResult(largeData);
return function() {
console.log(result); // Only holds result, not largeData
};
}
class Component {
mount() {
this.handler = () => { /* ... */ };
window.addEventListener('resize', this.handler);
}
unmount() {
window.removeEventListener('resize', this.handler); // ✅
}
}
  • 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