JavaScript’s single-threaded nature doesn’t mean slow performance. The event loop is key to understanding and optimizing JS apps.
Event Loop 101
- Call Stack: Executes synchronous code
- Task Queue: Holds callbacks (setTimeout, I/O)
- Microtask Queue: Promises, queueMicrotask()
- Event Loop: Orchestrates execution
console.log('1');
setTimeout(() => console.log('2'), 0);
Promise.resolve().then(() => console.log('3'));
console.log('4');
// Output: 1, 4, 3, 2
Performance Pitfalls
- Long-running tasks block the loop
- Excessive DOM manipulation
- Synchronous network requests
Optimization Techniques
- Use async/await for cleaner asynchronous code
async function fetchData() { const response = await fetch('https://api.example.com/data'); return response.json();
}
- Debounce expensive operations
const debounce = (fn, delay) => { let timeoutId; return (...args) => { clearTimeout(timeoutId); timeoutId = setTimeout(() => fn(...args), delay); };
};
- Use Web Workers for CPU-intensive tasks
const worker = new Worker('heavy-calculation.js');
worker.postMessage({data: complexData});
worker.onmessage = (event) => console.log(event.data);
- Virtualize long lists
- Use requestAnimationFrame for smooth animations
- Batch DOM updates
Measuring Performance
- Use Performance API
performance.mark('start');
// Code to measure
performance.mark('end');
performance.measure('My operation', 'start', 'end');
- Chrome DevTools Performance tab
- Lighthouse audits
Remember: The fastest code is often the code not written. Optimize wisely.
Cheers🥂
Discover more from Coursity
Subscribe to get the latest posts sent to your email.