Optimization
- Node.js course
- Advanced
- Lesson 17/83
- 5 min
Learn common performance optimizations.
Optimization techniques
Performance optimization in Node.js follows a few core approaches. First: measure. Always profile before optimizing; use data, not guesses. Second: remove the bottleneck. Move CPU-heavy work to a worker thread; make I/O asynchronous.
Third: cache. Keep repeated calculations in a cache. Fourth: batch. Do small operations in batches; for example write to a database in bulk, not one by one.
Loop optimization
Repeating the same calculation inside a loop is expensive. You speed it up by moving it outside the loop (loop-invariant code motion). For example, assign arr.length to a variable instead of reading it every iteration.
Also a for loop is generally faster than forEach; but the difference is usually small. Choose readability first, then measure; optimize only when there is a real gain. Premature optimization is a bad habit.
Practice Log the loop sum
Write a for loop from 0 to 4 (inclusive). Add i to sum each step. Log sum at the end.
Starter code
// reset sum to zero
// loop from 0 to 4
// log sumSample solution
let sum = 0;
for (let i = 0; i < 5; i++) { sum += i; }
console.log(sum);Expected output
10
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the loop start
for (let i = ____; i < 5; i++)
for (let i = 0; i < 5; i++)
Explanation: The loop starts at 0 and goes up to 5.
2 Match each piece to its role
| Term | Meaning |
|---|---|
loops |
Loop |
cache |
Cache |
async |
Asynchronous |
batch |
Bulk work |
3 What is the most effective optimization approach?
- Measure first, then optimize Correct answer
- Changing things at random
- Tahmin etmek
- Shortening the code
Explanation: Measuring first is the foundation of optimization.