Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
Performance optimization is the process of improving how fast your application runs, reducing resource usage, and providing a better user experience. It involves identifying bottlenecks, applying best practices, and measuring results to ensure your code runs efficiently.
Reduce initial load time and Time to Interactive
Smooth animations and instant user interactions
Reduced CPU, memory, and network consumption
| Metric | What It Measures | Good Score |
|---|---|---|
FCP | First Contentful Paint - When first content appears | < 1.8s |
LCP | Largest Contentful Paint - Main content loaded | < 2.5s |
FID | First Input Delay - Time until user can interact | < 100ms |
CLS | Cumulative Layout Shift - Visual stability | < 0.1 |
TTI | Time to Interactive - Fully interactive | < 3.8s |
Break up long tasks into smaller chunks to keep the UI responsive.
// BAD: Blocks main thread
function processLargeArray(items) {
items.forEach(item => {
// Heavy processing
processItem(item);
});
}
// GOOD: Use requestIdleCallback
function processLargeArray(items) {
let index = 0;
function processChunk() {
const startTime = performance.now();
while (index < items.length && performance.now() - startTime < 50) {
processItem(items[index]);
index++;
}
if (index < items.length) {
requestIdleCallback(processChunk);
}
}
requestIdleCallback(processChunk);
}Limit how often expensive functions are called.
// Debounce: Wait until user stops typing
function debounce(func, wait) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), wait);
};
}
const searchAPI = debounce((query) => {
fetch('/api/search?q=' + query);
}, 300);
input.addEventListener('input', (e) => searchAPI(e.target.value));
// Throttle: Limit execution frequency
function throttle(func, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
const handleScroll = throttle(() => {
console.log('Scroll position:', window.scrollY);
}, 100);
window.addEventListener('scroll', handleScroll);Cache expensive computation results.
// Memoization for expensive calculations
function memoize(fn) {
const cache = new Map();
return function(...args) {
const key = JSON.stringify(args);
if (cache.has(key)) {
return cache.get(key);
}
const result = fn.apply(this, args);
cache.set(key, result);
return result;
};
}
const expensiveCalculation = memoize((n) => {
console.log('Computing...');
return n * n * n;
});
console.log(expensiveCalculation(5)); // Computing... 125
console.log(expensiveCalculation(5)); // 125 (cached)Minimize reflows and repaints.
// BAD: Multiple reflows
for (let i = 0; i < 100; i++) {
const div = document.createElement('div');
div.textContent = i;
document.body.appendChild(div); // Reflow on each append
}
// GOOD: Batch DOM updates
const fragment = document.createDocumentFragment();
for (let i = 0; i < 100; i++) {
const div = document.createElement('div');
div.textContent = i;
fragment.appendChild(div);
}
document.body.appendChild(fragment); // Single reflow
// BAD: Reading and writing in loop (layout thrashing)
for (let i = 0; i < elements.length; i++) {
const width = elements[i].offsetWidth; // Read
elements[i].style.width = width + 10 + 'px'; // Write
}
// GOOD: Batch reads, then batch writes
const widths = elements.map(el => el.offsetWidth); // Batch reads
elements.forEach((el, i) => {
el.style.width = widths[i] + 10 + 'px'; // Batch writes
});Choose the right loop for the job.
// Fastest to slowest for large arrays:
// 1. for loop (fastest)
for (let i = 0; i < arr.length; i++) {
process(arr[i]);
}
// 2. for...of (good performance, readable)
for (const item of arr) {
process(item);
}
// 3. forEach (slower, but convenient)
arr.forEach(item => process(item));
// Cache array length
const len = arr.length;
for (let i = 0; i < len; i++) {
process(arr[i]);
}Load only what's needed, when it's needed.
// Dynamic imports
const button = document.getElementById('loadFeature');
button.addEventListener('click', async () => {
const module = await import('./heavy-feature.js');
module.initialize();
});
// React lazy loading
const HeavyComponent = React.lazy(() => import('./HeavyComponent'));
function App() {
return (
<Suspense fallback={<Loading />}>
<HeavyComponent />
</Suspense>
);
}<!-- Preload critical resources -->
<link rel="preload" href="critical.js" as="script">
<link rel="preload" href="hero-image.jpg" as="image">
<!-- Prefetch resources for next page -->
<link rel="prefetch" href="next-page.js">
<!-- Preconnect to external domains -->
<link rel="preconnect" href="https://api.example.com">
<!-- DNS prefetch -->
<link rel="dns-prefetch" href="https://cdn.example.com">// Performance API
const start = performance.now();
expensiveOperation();
const end = performance.now();
console.log('Took:', end - start, 'ms');
// Performance marks and measures
performance.mark('start-task');
doTask();
performance.mark('end-task');
performance.measure('task-duration', 'start-task', 'end-task');
const measures = performance.getEntriesByType('measure');
console.log(measures);
// Core Web Vitals
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
console.log('LCP:', entry.renderTime || entry.loadTime);
}
});
observer.observe({ type: 'largest-contentful-paint', buffered: true });
// Long Tasks API
const longTaskObserver = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
console.log('Long task detected:', entry.duration);
}
});
longTaskObserver.observe({ type: 'longtask', buffered: true });Split code, lazy load, remove unused code, use Web Workers
Avoid layout thrashing, use CSS transforms, virtualize long lists
Bundle files, use CDN, enable caching, compress assets
Clean up listeners, clear timers, avoid leaks, use weak references
Use Performance API, track Core Web Vitals, regular audits
Load above-the-fold content first, defer non-critical resources
Profile and identify bottlenecks before optimizing
Code splitting, lazy loading, compression
Debounce, memoize, efficient DOM updates
Track Core Web Vitals and set budgets