01 / 21

Algorithmic Improvements
vs. Micro-Optimizations

Learn when to rethink your approach entirely versus when to fine-tune existing code: the single most important judgment call in software performance.

JavaScript

What is Performance Optimization?

Performance optimization means making your code run faster or use fewer resources. But not all optimizations are created equal: some deliver massive speedups, while others barely make a difference.

Algorithmic Improvement
Changing the fundamental approach or data structure to reduce the growth rate of execution time.
Micro-Optimization
Tweaking low-level code details (loop style, caching a variable) without changing the overall approach.

Quick Refresher: Big-O Notation

Big-O describes how execution time grows as the input size \( n \) increases. It tells us the worst-case scaling behavior of an algorithm.

Input Size (n) Time
\( O(1) \)
\( O(\log n) \)
\( O(n) \)
\( O(n \log n) \)
\( O(n^2) \)

Why This Distinction Matters

Imagine searching for a name in a phone book with 1,000,000 entries. Compare two strategies:

Linear Search
Check every entry one by one. Worst case: 1,000,000 comparisons. Complexity: \( O(n) \).
Binary Search
Halve the remaining entries each step. Worst case: 20 comparisons. Complexity: \( O(\log n) \).

The Core Principle

Algorithmic Change
\( O(n^2) \to O(n \log n) \)
Changes the growth curve Impact: 100x-1000x+ vs Micro-Optimization
\( O(n^2) \to \text{still } O(n^2) \)
Shifts the constant factor Impact: 1.1x-3x

Algorithmic vs Micro: Key Differences

Algorithmic Improvement Micro-Optimization
What changes Algorithm or data structure Code-level implementation details
Big-O impact Changes the complexity class Same complexity class
Typical speedup 10x to 1,000,000x 1.05x to 3x
When it matters Large or growing datasets Hot loops in already-optimized code
Effort Higher: requires rethinking approach Lower: small, local code changes
Example Replace nested loop with a Set Use ++i instead of i++

How to Decide Which Approach

1
Profile first. Measure where time is actually spent. Never guess: use browser DevTools or console.time().
2
Identify the complexity. What is the Big-O of the slow section? Is it \( O(n^2) \), \( O(n \log n) \), or \( O(n) \)?
3
Ask: "Is there a better algorithm?" Can a different data structure (Map, Set, tree) or algorithm (sorting, binary search) reduce the Big-O?
4
If Big-O is already optimal, then micro-optimize: reduce constant factors, minimize allocations, avoid redundant work.
5
Benchmark again. Verify your changes actually improved real-world performance, not just theoretical complexity.

Example 1: Finding Duplicates

Given an array of \( n \) numbers, find if any value appears more than once.

// Naive approach: O(n²) function hasDuplicatesSlow(arr) { for (let i = 0; i < arr.length; i++) { for (let j = i + 1; j < arr.length; j++) { if (arr[i] === arr[j]) return true; } } return false; }

The Algorithmic Fix: Use a Set

// Algorithmic improvement: O(n) function hasDuplicatesFast(arr) { const seen = new Set(); for (const val of arr) { if (seen.has(val)) return true; seen.add(val); } return false; }
Before
\( O(n^2) \): nested loops comparing every pair. At \( n = 10{,}000 \): ~50M ops.
After
\( O(n) \): single pass with Set lookup. At \( n = 10{,}000 \): ~10K ops.

Example 2: Sorting 10,000 Items

You need to sort an array. Consider two different sorting algorithms:

Array Size (n) Operations 0 2500 5000 7500 10000
Bubble Sort \( O(n^2) \)
Merge Sort \( O(n \log n) \)

When Micro-Optimization Is Right

Your algorithm is already \( O(n) \). The profiler shows a specific line runs millions of times per frame in a game loop. Now micro-optimization makes sense:

// Before: unnecessary allocation each call function distance(a, b) { const diff = { x: a.x - b.x, y: a.y - b.y }; return Math.sqrt(diff.x ** 2 + diff.y ** 2); } // After: avoid object allocation function distanceFast(a, b) { const dx = a.x - b.x; const dy = a.y - b.y; return Math.sqrt(dx * dx + dy * dy); }

The Decision Flowchart

Code is too slow Profiled? No Profile first! Yes Can reduce Big-O? Yes Algorithmic Improvement No Micro- Optimization

Real-World Analogy

Imagine you need to deliver packages from New York to Los Angeles:

Micro-Optimization
Drive 5% faster on the highway. Saves ~2 hours on a 40-hour drive.
Algorithmic Improvement
Take a plane instead of driving. Saves ~35 hours. Completely different approach.

Examples in JavaScript

Scenario Algorithmic Fix Micro-Optimization
Find item in list Sort once, then use binary search for repeated lookups Use === over ==
Remove duplicates Use a Set Cache .length in loop
Count frequencies Use a Map Pre-allocate object keys
Build strings Use Array.join() Use template literals
Shortest path Dijkstra over brute force Use typed arrays for nodes

Common Mistakes

✕ Optimizing Without Profiling
Guessing which code is slow instead of measuring. You might optimize a function that takes 1% of total runtime.
✕ Micro-Optimizing \( O(n^2) \) Code
Making a nested loop 2x faster still leaves it at \( O(n^2) \). The right move is to eliminate the nesting.
✕ Premature Optimization
Spending hours on micro-optimizations before the code even works correctly. Get it right first, then make it fast.

Key Takeaways

1
Algorithmic improvements change the Big-O complexity and deliver exponential speedups as data grows.
2
Micro-optimizations reduce constant factors and only matter after the algorithm is already optimal.
3
Always profile first to find the actual bottleneck. Measure, do not guess.
4
Prefer better data structures (Set, Map, sorted arrays) before tweaking loop mechanics.
5
Benchmark after every change to confirm real improvement, not just theoretical improvement.

Question 1 of 5

A function uses two nested loops to check all pairs in an array, resulting in \( O(n^2) \) time. A developer replaces the inner loop with a Set lookup, reducing it to \( O(n) \). This is an example of:

Question 2 of 5

A developer changes for (let i = 0; i < arr.length; i++) to const len = arr.length; for (let i = 0; i < len; i++). What type of optimization is this?

Question 3 of 5

Your app is slow. You suspect the rendering function is the bottleneck but have not measured. What should you do first?

Question 4 of 5

An \( O(n^2) \) sorting algorithm is micro-optimized to run 2x faster. For \( n = 100{,}000 \), approximately how many operations does it perform compared to an \( O(n \log n) \) algorithm?

Question 5 of 5

You have an \( O(n) \) function that runs inside a game loop at 60fps. Profiling shows it allocates many temporary objects. Which optimization strategy is most appropriate?