01 / 20

Algorithmic Improvements
vs. Micro-Optimizations

Learn to recognize when your C++ code needs a better algorithm versus a low-level tweak: the single most important performance skill you can develop.

C++ Performance

What is an Algorithmic Improvement?

An algorithmic improvement changes the fundamental approach your code takes to solve a problem. It reduces the Big-O complexity class, meaning the number of operations grows more slowly as the input size \( n \) increases.

Before
Linear search through an unsorted array: \( O(n) \) per query
After
Sort once, then binary search: \( O(n \log n + q \log n) \) total

What is a Micro-Optimization?

A micro-optimization improves the constant factor of your code without changing its Big-O complexity. It makes each operation faster but doesn't change how the work scales with \( n \).

Examples
Loop unrolling, cache-friendly data layouts, avoiding virtual dispatch, using reserve() on vectors
Impact
Typically a 2x to 5x speedup: the Big-O stays the same, but the constant drops

Why This Distinction Matters

For small inputs, micro-optimizations can make a noticeable difference. But as \( n \) grows, the complexity class dominates. A well-optimized \( O(n^2) \) algorithm will always lose to a naive \( O(n \log n) \) algorithm at large enough \( n \).

Input size n Time
\(O(n^2)\) naive
\(O(n^2)\) optimized
\(O(n \log n)\) naive
crossover

The Core Rule

This is not just a guideline: it is a mathematical certainty. For any two complexity classes \( f(n) \) and \( g(n) \) where \( f(n) = o(g(n)) \), there exists an \( n_0 \) such that for all \( n > n_0 \):

No matter how large the constant \( c_2 \) on the better algorithm is, or how small the constant \( c_1 \) on the worse one, the lower complexity class always wins eventually.

Complexity Classes at a Glance

n Operations
\(O(1)\)
\(O(\log n)\)
\(O(n)\)
\(O(n \log n)\)
\(O(n^2)\)
\(O(2^n)\)

Algorithmic vs. Micro: Side by Side

Algorithmic Improvement Micro-Optimization
Changes Big-O? Yes No
Typical speedup 10x to 1000x+ 1.5x to 5x
Effect at scale Grows with \( n \) Constant factor
Code change New data structure / approach Tweak existing code
When to apply First After algorithm is correct
Example Hash map instead of nested loop reserve() on a vector

How to Decide What You Need

1
Profile first. Use a profiler to find the actual bottleneck: do not guess.
2
Identify the complexity. What is the Big-O of the hot function? Write it down.
3
Check if a lower class exists. Can you use a hash map, sorting, binary search, or a different data structure to reduce the complexity?
4
If yes: change the algorithm. This is your highest-leverage move.
5
If no: micro-optimize. You are already at the optimal complexity: now reduce the constant factor.

Example 1: Duplicate Finder

Problem: Given a vector of \( n \) integers, determine if any duplicates exist. A naive approach compares every pair.

// Naive: O(n²) bool hasDuplicate(const vector<int>& v) { for (int i = 0; i < v.size(); i++) for (int j = i+1; j < v.size(); j++) if (v[i] == v[j]) return true; return false; }

Example 1: The Algorithmic Fix

// Improved: O(n) average with a hash set bool hasDuplicate(const vector<int>& v) { unordered_set<int> seen; seen.reserve(v.size()); // micro-opt: pre-allocate for (int x : v) { if (!seen.insert(x).second) return true; } return false; }
Algorithm Change
Hash set lookup is \( O(1) \) average, so total is \( O(n) \) instead of \( O(n^2) \)
Micro-Optimization
reserve() pre-allocates memory to avoid rehashing: same \( O(n) \), lower constant

Example 2: Sorting Strategies

Scenario: You need to sort a million records. You start with bubble sort and it takes 20 minutes. What should you do?

✕
Micro-optimize bubble sort: Unroll the inner loop, use __builtin_expect, align data. Result: maybe 12 minutes. Still \( O(n^2) \).
✓
Switch to std::sort: Uses introsort, which is \( O(n \log n) \). Result: under 1 second. Done.

Example 3: When Micro-Optimization Wins

Scenario: You already use \( O(n) \) to sum a large array. Profile shows 80% of time is in this loop. Can you do better than \( O(n) \)?

// Already O(n) — can't reduce complexity double sum(const vector<double>& v) { double total = 0.0; for (auto x : v) total += x; return total; }

No: you must read every element at least once. But you can micro-optimize:

SIMD Vectorization
Use compiler flags (-O3 -march=native) to process 4+ doubles per cycle
Data Alignment
Align the array to cache-line boundaries for fewer cache misses
Prefetching
Hint the CPU to load the next chunk of data while processing the current one

The Decision Flowchart

Is it slow? Profile: find the bottleneck Can you reduce the Big-O? Yes Algorithmic Improvement No Micro- Optimization Measure again. Repeat.

Real-World Impact: The Numbers

How many operations does each approach take for various input sizes? Assume 1 operation = 1 nanosecond.

\( n \) \( O(n^2) \) \( O(n \log n) \) \( O(n) \)
1,000 1 ms \(10\,\mu\text{s}\) \(1\,\mu\text{s}\)
100,000 10 seconds 1.7 ms 0.1 ms
10,000,000 ~28 hours 233 ms 10 ms

Common Mistakes

✕ Optimizing Without Profiling
You spend hours tweaking a function that accounts for 2% of runtime. Always profile first to find the real bottleneck.
✕ Micro-Optimizing an \( O(n^2) \) Loop
Adding __builtin_expect or loop unrolling to a nested loop that should be replaced with a hash map. Fix the algorithm first.
✕ Premature Micro-Optimization
Sacrificing code readability for a 5% speedup before confirming the code is even the bottleneck. Knuth's famous rule applies here.

Question 1 of 5

Your program uses a nested loop to find matching pairs in two arrays of size \( n \). It runs in \( O(n^2) \). A colleague suggests using -O3 compiler optimization. What should you do first?

Question 2 of 5

You have an \( O(n \log n) \) sorting algorithm that is the bottleneck in your program. No sorting algorithm with lower complexity exists for comparison-based sorts. What type of optimization should you pursue?

Question 3 of 5

Which of the following is an example of an algorithmic improvement, not a micro-optimization?

Question 4 of 5

A student's code runs in \( O(2^n) \) and they add loop unrolling to the inner loop, achieving a 2x speedup. At \( n = 50 \), approximately how much time does this save?

Question 5 of 5

When is it appropriate to focus on micro-optimizations in C++?