Optimizing JavaScript Loops for Fast Performance
Learn proven techniques for optimizing JavaScript loops. Covers caching array length, reducing work per iteration, choosing the right loop type, avoiding DOM access in loops, and measuring performance with benchmarks.
Loop performance matters when your code runs over thousands or millions of items. A small inefficiency inside a loop body gets multiplied by every iteration, turning a trivial cost into a noticeable delay. The good news: most loop optimizations in JavaScript are straightforward. Caching values, picking the right loop type, reducing work per iteration, and avoiding unnecessary DOM access can transform sluggish code into something fast and responsive.
This tutorial covers practical optimization techniques for JavaScript loops, from beginner-friendly fixes to more advanced patterns. Every technique includes before-and-after code so you can see exactly what changes and why it matters.
When Optimization Actually Matters
Before optimizing anything, understand where it matters:
| Iteration count | Optimization priority | Example |
|---|---|---|
| Under 100 | Not needed | Navigation menu items |
| 100 to 1,000 | Low priority | Table rows on a page |
| 1,000 to 10,000 | Worth considering | Large dataset filtering |
| 10,000 to 100,000 | Important | CSV processing, search indexing |
| Over 100,000 | Critical | Data analysis, canvas rendering |
Measure First
Do not optimize loops that run fewer than 1,000 times unless they execute frequently (such as inside animation frames). Premature optimization makes code harder to read without measurable benefit. Always measure before and after any change.
Technique 1: Cache the Array Length
Accessing .length on every iteration forces the engine to look it up each time. Caching it in a variable avoids repeated property access:
// Before: length checked every iteration
for (let i = 0; i < items.length; i++) {
process(items[i]);
}
// After: length cached once
for (let i = 0, len = items.length; i < len; i++) {
process(items[i]);
}Modern engines optimize .length access on standard arrays, so the difference is small for simple arrays. But for HTMLCollection and NodeList objects (which are live collections), caching is essential:
// HTMLCollection: live, recalculated on every .length access
const divs = document.getElementsByTagName("div");
// Slow: divs.length recalculates if DOM changes
for (let i = 0; i < divs.length; i++) {
divs[i].classList.add("processed");
}
// Fast: cache once
for (let i = 0, len = divs.length; i < len; i++) {
divs[i].classList.add("processed");
}Technique 2: Reduce Work Per Iteration
Every operation inside the loop body runs on every iteration. Moving invariant calculations outside the loop reduces total work:
// Before: creating regex and calculating discount every iteration
const orders = getOrders();
for (let i = 0; i < orders.length; i++) {
const pattern = new RegExp("^PROMO-\\d+$");
const discount = getBaseDiscount() * getMultiplier();
if (pattern.test(orders[i].code)) {
orders[i].total -= discount;
}
}
// After: move invariants outside the loop
const orders = getOrders();
const pattern = new RegExp("^PROMO-\\d+$");
const discount = getBaseDiscount() * getMultiplier();
for (let i = 0; i < orders.length; i++) {
if (pattern.test(orders[i].code)) {
orders[i].total -= discount;
}
}Common Invariants to Hoist
| What to move out | Why |
|---|---|
new RegExp(...) | Creating regex objects is expensive |
| DOM queries | querySelector searches the entire DOM each call |
Math.pow(), Math.sqrt() | Constant math operations with fixed inputs |
JSON.parse() of static data | Parsing runs the same result each time |
| Date formatting setup | Intl.DateTimeFormat creation is slow |
Technique 3: Choose the Right Loop Type
Different loop types have different performance profiles. Understanding the while loop alongside the for loop helps you pick the right tool:
const arr = Array.from({ length: 100000 }, (_, i) => i);
// 1. Classic for loop (fastest for indexed access)
for (let i = 0; i < arr.length; i++) {
arr[i];
}
// 2. for...of (clean syntax, slight overhead)
for (const item of arr) {
item;
}
// 3. forEach (function call overhead per iteration)
arr.forEach((item) => {
item;
});
// 4. while loop (equivalent to for when structured similarly)
let i = 0;
while (i < arr.length) {
arr[i];
i++;
}Loop Speed Comparison Table
| Loop type | Relative speed | Break support | Best for |
|---|---|---|---|
for | Fastest | Yes | Index-based iteration, performance-critical code |
while | Same as for | Yes | Unknown iteration count |
for...of | Slightly slower | Yes | Clean syntax, iterables |
forEach | Slowest | No | Readability when performance is not critical |
Speed vs Readability
The difference between loop types is usually microseconds per iteration. Choose for...of or forEach for readability in most code. Switch to classic for loops only when profiling shows the loop is a bottleneck.
Technique 4: Avoid DOM Access Inside Loops
DOM operations are orders of magnitude slower than pure JavaScript operations. Batch DOM changes instead of making one per iteration:
// Slow: 1,000 individual DOM updates
const list = document.getElementById("results");
for (let i = 0; i < 1000; i++) {
const li = document.createElement("li");
li.textContent = `Item ${i}`;
list.appendChild(li); // triggers layout recalculation each time
}
// Fast: build in memory, attach once
const list = document.getElementById("results");
const fragment = document.createDocumentFragment();
for (let i = 0; i < 1000; i++) {
const li = document.createElement("li");
li.textContent = `Item ${i}`;
fragment.appendChild(li); // no layout impact
}
list.appendChild(fragment); // single DOM updateOther DOM Batching Patterns
// Build HTML string, set innerHTML once
const items = getData();
let html = "";
for (const item of items) {
html += `<li>${item.name}</li>`;
}
document.getElementById("list").innerHTML = html;// Batch style changes
const elements = document.querySelectorAll(".card");
// Slow: forced reflow on each iteration
for (const el of elements) {
el.style.width = el.offsetWidth + 10 + "px"; // read + write = reflow
}
// Fast: read all, then write all
const widths = [];
for (const el of elements) {
widths.push(el.offsetWidth); // read phase
}
for (let i = 0; i < elements.length; i++) {
elements[i].style.width = widths[i] + 10 + "px"; // write phase
}Technique 5: Use Early Termination
When searching or validating, stop as soon as you have the answer. The break statement is your primary tool for early termination:
// Slow: processes entire array even after finding the target
function findUser(users, id) {
let result = null;
for (const user of users) {
if (user.id === id) {
result = user;
}
}
return result;
}
// Fast: returns immediately on match
function findUser(users, id) {
for (const user of users) {
if (user.id === id) {
return user;
}
}
return null;
}The same applies to nested loops. Breaking out of both loops prevents unnecessary iterations:
function findInGrid(grid, target) {
for (let row = 0; row < grid.length; row++) {
for (let col = 0; col < grid[row].length; col++) {
if (grid[row][col] === target) {
return { row, col }; // exits both loops
}
}
}
return null;
}Technique 6: Replace Nested Loops with Lookup Structures
Nested loops that compare elements often hide an O(n^2) pattern that can be reduced to O(n):
// O(n^2): nested loop comparison
function findCommon(arr1, arr2) {
const result = [];
for (const a of arr1) {
for (const b of arr2) {
if (a === b) result.push(a);
}
}
return result;
}
// O(n): Set-based lookup
function findCommon(arr1, arr2) {
const set = new Set(arr2);
const result = [];
for (const a of arr1) {
if (set.has(a)) result.push(a);
}
return result;
}When to Use Which Data Structure
| Original pattern | Optimized with | Time improvement |
|---|---|---|
| Check if value exists in array | Set.has() | O(n) to O(1) per check |
| Match by key in array | Map.get() | O(n) to O(1) per lookup |
| Group items by property | Map with arrays | O(n^2) to O(n) |
| Sort then binary search | Pre-sorted array | O(n) to O(log n) per search |
Technique 7: Process in Chunks
For very large datasets, processing everything in one loop can freeze the UI. Split the work across multiple frames:
function processInChunks(items, chunkSize, processItem) {
let index = 0;
function nextChunk() {
const end = Math.min(index + chunkSize, items.length);
for (; index < end; index++) {
processItem(items[index]);
}
if (index < items.length) {
requestAnimationFrame(nextChunk);
}
}
nextChunk();
}
// Usage: process 100 items per frame
const bigArray = Array.from({ length: 50000 }, (_, i) => i);
processInChunks(bigArray, 100, (item) => {
// heavy processing per item
});Measuring Loop Performance
Use performance.now() for accurate timing:
const data = Array.from({ length: 100000 }, (_, i) => i);
const start = performance.now();
let sum = 0;
for (let i = 0; i < data.length; i++) {
sum += data[i];
}
const end = performance.now();
console.log(`Time: ${(end - start).toFixed(2)}ms`);
console.log(`Sum: ${sum}`);Benchmark Comparison Helper
function benchmark(name, fn, iterations = 10) {
const times = [];
for (let run = 0; run < iterations; run++) {
const start = performance.now();
fn();
times.push(performance.now() - start);
}
const avg = times.reduce((a, b) => a + b, 0) / times.length;
const min = Math.min(...times);
const max = Math.max(...times);
console.log(`${name}: avg=${avg.toFixed(2)}ms min=${min.toFixed(2)}ms max=${max.toFixed(2)}ms`);
}
// Compare approaches
const arr = Array.from({ length: 100000 }, (_, i) => i);
benchmark("for loop", () => {
let sum = 0;
for (let i = 0; i < arr.length; i++) sum += arr[i];
});
benchmark("for...of", () => {
let sum = 0;
for (const n of arr) sum += n;
});
benchmark("forEach", () => {
let sum = 0;
arr.forEach((n) => (sum += n));
});
benchmark("reduce", () => {
arr.reduce((a, b) => a + b, 0);
});Quick Reference: Optimization Checklist
| Check | Action |
|---|---|
| Live HTMLCollection? | Cache .length before the loop |
| Regex/object creation inside loop? | Move to before the loop |
| DOM writes on every iteration? | Use DocumentFragment or string building |
| Read + write DOM in same iteration? | Separate read phase from write phase |
| Searching for one item? | Add break or return on match |
| Nested loop comparing elements? | Replace inner loop with Set or Map |
| Over 100K items freezing the UI? | Process in chunks with requestAnimationFrame |
| Not sure if optimization helped? | Measure with performance.now() |
Rune AI
Key Insights
- Measure before optimizing: use
performance.now()to confirm a loop is actually slow - Cache live collection lengths:
HTMLCollection.lengthrecalculates on every access - Move invariants outside loops: regex creation, DOM queries, and constant calculations should not repeat
- Batch DOM operations: use DocumentFragment or build HTML strings to avoid per-iteration reflows
- Use Sets and Maps: replace nested comparison loops with O(1) lookups for dramatic speedups
Frequently Asked Questions
Does caching array length really make a difference?
Is forEach slower than a for loop?
Should I use map/filter/reduce instead of loops?
How do I know if my loop is a performance problem?
What about Web Workers for heavy loops?
Conclusion
Loop optimization starts with measuring, not guessing. Cache loop bounds for live DOM collections, move invariant calculations outside the loop body, batch DOM operations using DocumentFragment or string building, and use early termination when searching. For comparison-heavy code, replace nested loops with Sets and Maps to drop from quadratic to linear time. These techniques require minimal code changes but produce measurable improvements on large datasets.
More in this topic
OffscreenCanvas API in JS for UI Performance
Master the OffscreenCanvas API to offload rendering from the main thread. Covers worker-based 2D and WebGL rendering, animation loops inside workers, bitmap transfer, double buffering, chart rendering pipelines, image processing, and performance measurement strategies.
Advanced Web Workers for High Performance JS
Master Web Workers for truly parallel JavaScript execution. Covers dedicated and shared workers, structured cloning, transferable objects, SharedArrayBuffer with Atomics, worker pools, task scheduling, Comlink RPC patterns, module workers, and performance profiling strategies.
JavaScript Macros and Abstract Code Generation
Master JavaScript code generation techniques for compile-time and runtime metaprogramming. Covers AST manipulation, Babel plugin authorship, tagged template literals as macros, code generation pipelines, source-to-source transformation, compile-time evaluation, and safe eval alternatives.