01 / 21

Algorithmic Improvements
vs. Micro-Optimizations

Learn to recognize when your code needs a better algorithm versus a faster implementation: the skill that separates good engineers from great ones.

Java

What Is Performance Optimization?

Performance optimization means making code run faster or use less memory. But not all optimizations are created equal. There are two fundamentally different strategies:

Algorithmic Improvement
Changing the underlying approach to reduce the growth rate of time or space: e.g., replacing \(O(n^2)\) with \(O(n \log n)\).
Micro-Optimization
Tweaking constants and low-level details without changing Big-O: e.g., using a faster loop construct or caching a value.

Why Big-O Dominates at Scale

As input size \(n\) grows, the order of growth overwhelms any constant-factor speedup. A micro-optimization might make your code 2x faster, but an algorithmic improvement can make it thousands of times faster.

Input size \((n)\)
Time
\(O(n^2)\)
\(O(n \log n)\)
\(O(n^2)/2\)

An Analogy: Finding a Word

Imagine searching for a word in a dictionary with \(n = 100{,}000\) entries:

Linear Scan
Read every entry from page 1. Average: 50,000 checks. Reading faster (micro-optimization) still means thousands of checks.
Binary Search
Open to the middle, eliminate half. Only \(\lceil \log_2 100{,}000 \rceil = \) 17 checks. That is an algorithmic improvement.

The Core Rule

First, optimize the ALGORITHM
(reduce Big-O complexity).
Then, and only then, consider micro-optimizations
(reduce constant factors).
1 2

Growth Rates: Numbers Don't Lie

\(n\) \(O(\log n)\) \(O(n)\) \(O(n \log n)\) \(O(n^2)\)
1031033100
1,000101,00010,0001,000,000
100,00017100,0001,700,00010,000,000,000
10,000,0002310M233M100 trillion

Algorithmic vs. Micro: Side by Side

Aspect Algorithmic Improvement Micro-Optimization
Changes Big-O?YesNo
ExampleBubble Sort → Merge Sorti++ → ++i
Impact at small \(n\)Often minimalCan matter
Impact at large \(n\)DramaticMarginal
EffortRedesign approachTweak existing code
When to applyFirstAfter profiling

How to Decide Which You Need

1
Identify the bottleneck. Use a profiler or reason about your code's Big-O complexity.
2
Ask: "Can I reduce the Big-O?" If you are doing \(O(n^2)\) nested loops where \(O(n \log n)\) or \(O(n)\) is possible, that is your priority.
3
If Big-O is already optimal, profile for hotspots and apply targeted micro-optimizations.
4
Measure after every change. Never assume a micro-optimization helped: benchmark it.

The Decision Flowchart

Code is too slow
Is Big-O
already optimal?
No
Improve
Algorithm
Yes
Profile: is there
a constant-factor hotspot?
Yes
Micro-
Optimize
No
Code is fine: ship it!

Example 1: Finding Duplicates

Problem: Given an array of \(n\) integers, determine if any value appears more than once.

// Brute force: O(n²) for (int i = 0; i < arr.length; i++) for (int j = i + 1; j < arr.length; j++) if (arr[i] == arr[j]) return true;
// HashSet approach: O(n) Set<Integer> seen = new HashSet<>(); for (int x : arr) if (!seen.add(x)) return true;

Example 2: Sorting 1 Million Items

With \(n = 1{,}000{,}000\), compare two strategies:

Selection Sort
\(O(n^2) = 10^{12}\) operations. Even at 1 billion ops/sec, this takes ~17 minutes.
Merge Sort
\(O(n \log n) \approx 2 \times 10^{7}\) operations. At the same speed: ~0.02 seconds.

When Micro-Optimizations Do Matter

Once your algorithm is optimal, constant factors can matter for performance-critical code. Here is a real Java example:

// Slow: String concatenation in a loop - actually O(n²)! String result = ""; for (int i = 0; i < n; i++) result += items[i]; // Creates new String each time!
// Fast: StringBuilder - O(n) StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) sb.append(items[i]); String result = sb.toString();

True Micro-Optimizations in Java

These changes do not alter Big-O, but reduce constant factors:

1
Using ArrayList vs. LinkedList for sequential access: same \(O(n)\) traversal, but ArrayList has better cache locality.
2
Pre-sizing collections: new ArrayList<>(1000) avoids internal array resizing, saving a constant factor.
3
Caching array.length in a local variable before a loop: avoids repeated field access.
4
Using primitives (int) over wrappers (Integer): avoids boxing/unboxing overhead.

Example: Shortest Path

Problem: Find the shortest path in a weighted graph with \(V\) vertices and \(E\) edges.

Naive Approach
Check all possible paths: \(O(V!)\) in the worst case. Completely impractical for even \(V = 20\).
Dijkstra's Algorithm
\(O((V + E) \log V)\) with a priority queue. Handles millions of vertices easily.

Common Mistakes

✕ Premature Micro-Optimization
Spending hours tweaking loop variables or bit-shifting when the algorithm itself is \(O(n^2)\) and should be \(O(n \log n)\).
✕ Ignoring Data Structures
Using an ArrayList for frequent contains() checks: that is \(O(n)\) per call. A HashSet makes it \(O(1)\).
✕ Optimizing Without Measuring
Assuming a change is faster without benchmarking. The JVM's JIT compiler often optimizes away the "improvement" you thought you made.

Summary Cheat Sheet

Symptom Likely Fix Type
Runtime doubles when input doubles\(O(n)\) is fine: profile constantsMicro
Runtime quadruples when input doublesYou have \(O(n^2)\): find a better algorithmAlgorithmic
Works for 100 items, breaks at 10,000Almost certainly a Big-O problemAlgorithmic
Consistently 2x slower than expectedProfile: maybe bad data structure or I/OMicro
Nested loops over the same collectionCan you use a HashMap/HashSet?Algorithmic
Lots of object creation in a tight loopReuse objects or use primitivesMicro

Question 1 of 5

A program searches for a value in an unsorted array using a linear scan (\(O(n)\)). A developer proposes "unrolling" the loop to check 4 elements per iteration. This is an example of:

Question 2 of 5

A method checks if a sorted array contains a target by iterating from index 0 to \(n-1\). To improve performance, you should first:

Question 3 of 5

A program counts how many pairs \((i, j)\) in an array sum to a target \(k\) using two nested loops. Which change is an algorithmic improvement?

Question 4 of 5

Your code already uses an optimal \(O(n \log n)\) sorting algorithm, but it's still slower than expected. What should you do next?

Question 5 of 5

Which of the following is the best summary of when to apply micro-optimizations?