10-1 Code Optimization Techniques
Key Concepts
- Minimizing DOM Manipulation
- Using Efficient Data Structures
- Avoiding Global Variables
- Leveraging Event Delegation
- Optimizing Loops
- Using Memoization
- Lazy Loading
- Tree Shaking
- Code Splitting
- Using Web Workers
Minimizing DOM Manipulation
Minimizing DOM manipulation involves reducing the number of times the DOM is accessed or updated. This can be achieved by batching updates or using document fragments.
Example:
let fragment = document.createDocumentFragment(); for (let i = 0; i < 1000; i++) { let div = document.createElement('div'); div.textContent = 'Item ' + i; fragment.appendChild(div); } document.body.appendChild(fragment);
Analogies: Think of DOM manipulation as moving furniture. Moving one piece at a time is slow, but moving multiple pieces together is faster.
Using Efficient Data Structures
Using efficient data structures involves choosing the right data structure for the task at hand. For example, using a Set for unique values or a Map for key-value pairs.
Example:
let uniqueNumbers = new Set([1, 2, 2, 3, 3, 4]); console.log([...uniqueNumbers]); // Outputs: [1, 2, 3, 4]
Analogies: Data structures are like different types of containers. Using the right container (e.g., a box vs. a bag) makes tasks easier and faster.
Avoiding Global Variables
Avoiding global variables involves limiting the scope of variables to prevent unintended side effects and improve maintainability. This can be achieved using closures or modules.
Example:
(function() { let counter = 0; function increment() { counter++; console.log(counter); } increment(); })();
Analogies: Global variables are like public announcements. They can be heard by everyone, leading to confusion and noise.
Leveraging Event Delegation
Leveraging event delegation involves attaching event listeners to parent elements instead of individual child elements. This reduces the number of event listeners and improves performance.
Example:
document.getElementById('parent').addEventListener('click', function(event) { if (event.target.matches('li')) { console.log('You clicked on an item'); } });
Analogies: Event delegation is like having one security guard watch over a whole room instead of multiple guards for each item.
Optimizing Loops
Optimizing loops involves reducing the complexity of loop operations. This can be achieved by minimizing the work done inside the loop or using more efficient looping constructs.
Example:
let arr = [1, 2, 3, 4, 5]; let sum = 0; for (let i = 0; i < arr.length; i++) { sum += arr[i]; } console.log(sum); // Outputs: 15
Analogies: Optimizing loops is like streamlining a production line to reduce bottlenecks and improve efficiency.
Using Memoization
Using memoization involves caching the results of expensive function calls and reusing them when the same inputs occur again. This reduces redundant computations.
Example:
function memoize(fn) { let cache = {}; return function(n) { if (n in cache) { return cache[n]; } else { let result = fn(n); cache[n] = result; return result; } }; } let fib = memoize(function(n) { if (n <= 1) return n; return fib(n - 1) + fib(n - 2); }); console.log(fib(10)); // Outputs: 55
Analogies: Memoization is like taking notes during a lecture. You can refer to your notes instead of re-listening to the entire lecture.
Lazy Loading
Lazy loading involves deferring the loading of non-critical resources until they are needed. This improves the initial load time of the application.
Example:
function loadImage(url) { let img = new Image(); img.src = url; document.body.appendChild(img); } window.addEventListener('scroll', function() { if (window.scrollY + window.innerHeight >= document.body.offsetHeight) { loadImage('image.jpg'); } });
Analogies: Lazy loading is like ordering food at a buffet. You only take what you need when you need it, instead of taking everything at once.
Tree Shaking
Tree shaking involves removing unused code from the final bundle. This reduces the size of the application and improves load times.
Example:
// In a module system, only the used functions are included in the final bundle import { add } from './math'; console.log(add(2, 3)); // Outputs: 5
Analogies: Tree shaking is like pruning a tree. You remove the dead branches (unused code) to make the tree (application) healthier and more efficient.
Code Splitting
Code splitting involves dividing the application code into smaller chunks that can be loaded on demand. This reduces the initial load time and improves performance.
Example:
import('./module').then(module => { module.default(); });
Analogies: Code splitting is like breaking a large meal into smaller courses. You eat (load) what you need, when you need it.
Using Web Workers
Using Web Workers involves offloading CPU-intensive tasks to a background thread, freeing up the main thread to handle user interactions and rendering.
Example:
let worker = new Worker('worker.js'); worker.postMessage('Start calculation'); worker.onmessage = function(event) { console.log('Result: ' + event.data); };
Analogies: Web Workers are like hiring extra help. They handle the heavy lifting (calculations) while you focus on the main tasks (user interface).