1. Avoid Object Allocations Inside Loops
Creating new objects in tight loops increases memory pressure and slows down garbage collection (GC).
Example:
for (let i = 0; i < 1000; i++) { const obj = { value: i }; }
Youโre allocating 1,000 new objects โ and GC has to clean them up.
Better (when reusability is possible):
const obj = {}; for (let i = 0; i < 1000; i++) { obj.value = i; // reuse obj }
โ Why it matters: Less GC = faster execution and lower memory usage.
2. Cache Nested Property Access
Repeated access to nested properties triggers multiple lookups.
Example:
const total = user.profile.details.orders.length;
This traverses multiple object layers every time.
Better:
const orders = user.profile.details.orders; const total = orders.length;
โ Why it matters: Property lookup in JavaScript is dynamic and can be expensive, especially inside loops.
3. Chaining map() + filter() Can Be Costly
Yes, functional methods are elegant, but they often iterate more than needed:
const result = data.map(fn).filter(Boolean); // Two iterations
Faster alternative (for large arrays):
const result = []; for (const item of data) { const transformed = fn(item); if (transformed) result.push(transformed); }
โ Why it matters: Combining into a single pass reduces time complexity and boosts performance on large datasets.
4. Don't Expect setTimeout(fn, 0) to Be Immediate
Many devs use:
setTimeout(() => { doSomething(); }, 0);
..expecting immediate execution. But browsers enforce a minimum delay, often 4ms or more.
Faster microtask alternatives
Promise.resolve().then(doSomething); // or queueMicrotask(doSomething);
โ Why it matters: Microtasks run before the next rendering tick, ideal for ultra-fast UI reactions.
5. Lazy Load Expensive Code
Large functions or libraries that aren't always used? Donโt import them by default.
โ Bad:
if (condition) { heavyFn(); }
โ
Better:
if (condition) { import('./heavyFn.js').then(mod => mod.default()); }
This is especially useful in SPAs or client-heavy React/Vue apps.
โ Why it matters: Reduces initial bundle size and improves Time to Interactive (TTI).
6. Avoid forEach() in Performance-Critical Loops
forEach() is elegant but slower than traditional loops.
Benchmarks consistently show:
for (let i = 0; i < arr.length; i++) { ... }
...is faster than:
arr.forEach(item => { ... });
โ Why it matters: With large arrays or intensive operations, for, for...of, or even while offer better performance.
7. Donโt Guess Performance โ Measure It
Developers often โoptimizeโ based on assumptions. Donโt. Use:
console.time("process"); // code block console.timeEnd("process");
Recommended tools:
๐ฌ jsbench.me โ create and share benchmarks
๐งช Chrome DevTools > Performance tab โ for real-world profiling
๐ Lighthouse โ for web performance audits
โ
Why it matters: Real profiling reveals hidden bottlenecks. You can't fix what you can't measure.
Top comments (0)