⚡
Performance Optimization
Advanced
140 XP
60 min
Lesson Content
Performance Optimization
Writing efficient JavaScript is crucial for fast web applications. Learn techniques to optimize your code.
Debouncing and Throttling
// Debounce - Execute after delay
function debounce(func, delay) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func(...args), delay);
};
}
// Throttle - Execute at most once per period
function throttle(func, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
func(...args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}Memoization
function memoize(fn) {
const cache = {};
return function(...args) {
const key = JSON.stringify(args);
if (cache[key]) return cache[key];
cache[key] = fn(...args);
return cache[key];
};
}Lazy Loading
// Load resources only when needed
const loadModule = () => import('./module.js');Virtual Scrolling
Render only visible items in long lists to improve performance.
Example Code
Implement performance optimization techniques
// Debounce
function debounce(func, delay) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func(...args), delay);
};
}
const debouncedLog = debounce((msg) => console.log(msg), 300);
debouncedLog('Hello');
debouncedLog('World'); // Only this will execute
// Memoization
function memoize(fn) {
const cache = {};
return function(...args) {
const key = JSON.stringify(args);
if (cache[key]) {
console.log('Cache hit');
return cache[key];
}
console.log('Computing...');
cache[key] = fn(...args);
return cache[key];
};
}
const slowAdd = memoize((a, b) => a + b);
console.log(slowAdd(2, 3));
console.log(slowAdd(2, 3)); // CachedExpected Output:
World Computing... 5 Cache hit 5
Study Tips
- •Read the theory content thoroughly before practicing
- •Review the example code to understand key concepts
- •Proceed to the Practice tab when you're ready to code