JavaScript is the lingua franca of the web, but even the most seasoned devs can fall into the trap of writing code that feels like it took an eternity to run. Here’s a quick rundown of the low‑down to keep your scripts lean, mean, and blazing fast.
1️⃣ Use the right data structures
Arrays are fast for indexed access. Objects are fast for key‑value lookups. Don’t mix them if you can help it. The Map
and Set
types introduced in ES6 are great for unique collections and key/value pairs where string keys won’t cut it.
const users = new Map(); // O(1) lookup
users.set('alice', {age: 30});
console.log(users.get('alice').age); // 30
2️⃣ Avoid excessive DOM manipulation
Each appendChild
or style change forces a re‑flow. Batch your changes, or use a DocumentFragment
when inserting many nodes.
const frag = document.createDocumentFragment();
for (let i = 0; i < 1000; i++) {
const div = document.createElement('div');
div.textContent = i;
frag.appendChild(div);
}
document.body.appendChild(frag); // one reflow
3️⃣ Cache selectors
Querying the DOM repeatedly is expensive. Store the element reference.
const btn = document.getElementById('start');
btn.addEventListener('click', () => {/* ... */});
4️⃣ Leverage Web Workers
Heavy calculations can block the main thread. Offload them to a worker and keep the UI snappy.
// worker.js
self.onmessage = e => {
const result = heavyCalc(e.data);
postMessage(result);
};
5️⃣ Use async/await wisely
Await pauses the function. If you can fire multiple promises in parallel, Promise.all
beats awaiting sequentially.
async function loadData() {
const [user, posts] = await Promise.all([
fetch('/user').then(r=>r.json()),
fetch('/posts').then(r=>r.json())
]);
// use both results
}
Want to see a real‑world example? Check out this tiny demo that measures how fast you can render a list of 10,000 items.
Bonus: Use a profiler
Chrome DevTools > Performance tab. Record a short session and look for layout thrashing or JavaScript GC spikes. That’s where the rubber meets the road.
Ready to put these tips into practice? Try refactoring a piece of your old code and watch the performance numbers jump. Happy hacking!