Batch Operations vs Individual Updates
What You'll Learn
You'll discover why grouping changes together and applying them all at once can be orders of magnitude faster than making changes one item at a time.
The Restaurant Kitchen Analogy
Imagine a kitchen that serves one plate, cleans it, serves another plate, cleans it—versus a kitchen that serves all plates at once, then cleans them all together. The second approach minimizes setup/teardown overhead and is dramatically more efficient.
Why Individual Updates Are Costly
When you update items one at a time in a loop, you often pay hidden costs:
- DOM reflows: Each change can trigger a layout recalculation
- Event emissions: Triggering change events repeatedly
- Validation overhead: Running the same checks multiple times
- Transaction costs: Database or API calls in a loop
// Slow: Individual DOM updates
items.forEach(item => {
const div = document.createElement('div');
div.textContent = item;
container.appendChild(div); // Layout recalculated each time!
});
The Batch Approach
Instead, accumulate all changes, then apply them once:
// Fast: Single batch update
const fragment = document.createDocumentFragment();
items.forEach(item => {
const div = document.createElement('div');
div.textContent = item;
fragment.appendChild(div); // No layout cost yet
});
container.appendChild(fragment); // Layout calculated once
This same principle applies to:
- Array operations (build new array vs pushing repeatedly)
- Database writes (bulk insert vs individual inserts)
- State updates in frameworks (batched setState)
The Performance Gap
For 1,000 items, batching can be 10-100x faster depending on the operation. The more expensive each individual update, the bigger the win.
Key Takeaway: When processing multiple items, always consider whether you can collect all changes first and apply them in a single batch operation—the performance difference can be dramatic, especially as data scales.