Concept Explanation
An extra 1 second of loading time can cost a company millions in lost users. JavaScript is often the slowest part of a website. Efficient code makes the site feel "Snappy" and saves battery on mobile phones.
Key Strategies
- Minimize DOM access: Reading the DOM is 100x slower than reading a variable. Do your math in JS, then update the DOM once at the end.
- Debouncing: If a user is typing in a search box, don't run the search on every keystroke. Wait 300ms for them to stop typing.
- Lazy Loading: Don't load the JavaScript for the "Settings Page" until the user actually clicks the Settings button.
Syntax: The Debounce Pattern
function debounce(func, delay) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => func(...args), delay);
};
}
const processSearch = debounce(() => console.log("Searching..."), 500);
Best Practices
- Web Workers for Math: If you have to calculate something heavy, do it in a Web Worker (separate thread) so the UI doesn't freeze.
- Avoid 'with' and 'eval': These keywords make it impossible for the browser to optimize your code.
- Prefer Native Methods: Built-in methods like
.map()and.filter()are often faster and cleaner than manualforloops.
Practice Exercises
- The Loop Optimizer: Rewrite a nested
forloop using a "Map" or "Set" to achieve O(n) performance. - The Memory Profiler: Use the "Memory" tab in Chrome DevTools to take a snapshot of your app and look for "Leaked" variables.
- The Lazy Load: Research
import()syntax and explain how it allows for "Dynamic Imports" in modern JS.