name: performance-optimization description: Optimize slow code — profiling workflow, bottleneck identification, measurement-driven optimization. Use when existing code is too slow and you need to systematically find and fix hotspots. license: MIT
Three Philosophies of Optimization
See /efficient-code skill for the foundational philosophy. This skill covers advanced techniques after non-pessimization is applied.
1. Real Optimization
Benchmarking, measuring, comparing to theoretical maximum, profiling hot paths. This is expensive and rarely needed. Only do this after non-pessimization.
2. Non-Pessimization
The default approach. Write the simplest code that works without introducing unnecessary work. See /efficient-code skill. This gives 100-1000x improvements.
3. Fake Optimization
Repeating heard advice without understanding or measurement. Avoid.
Key insight: Most code is 100-1000x slower than hardware can handle because it adds unnecessary work. Non-pessimization fixes this. Real optimization is only needed after that.
What I do
Guide performance analysis and optimization. Use when investigating slow code, optimizing algorithms, or improving throughput.
You Get What You Measure
What you measure shapes outcomes. Measure:
- Memory usage: If ignored → wasteful allocation
- Frame performance: If ignored → dropped frames
- Build times: If ignored → slower iteration
- Test coverage: If ignored → untested paths
Optimization Mindset
Correctness First
Always start with an algorithm that is definitely correct, even if too slow.
"Even when writing fast code always start with an algorithm that is definitely correct. Because even if it's too slow, we can still try to optimize it. Whereas an algorithm that's not correct—it doesn't really matter how fast it is, because it doesn't give us the right answer."
Wrong code cannot be optimized into right code. Get correct first, optimize after.
Two Axes of Optimization
- Drive faster: Use techniques like multi-threading, SIMD - same work, less time
- Find a better route: Less work - better algorithms, domain knowledge, fewer operations
Always try "find a better route" first. Doing less is often more effective than doing the same faster.
Optimization Workflow
- Measure: Profile before optimizing, identify actual bottlenecks
- Analyze: Understand why code is slow, check for unnecessary work
- Optimize: One change at a time, measure impact
- Verify: Tests still pass, performance improved
Domain Knowledge Pruning
Use problem-specific constraints to skip impossible paths:
- If state X cannot possibly beat current best, skip exploring it
- Compute upper bounds: "worst case, how many more geodes could I get?"
- If upper bound ≤ current maximum, prune that branch
Example from a game state space:
// Upper bound calculation
time_remaining = max_turns - current_turn
max_possible = current_geodes + (geode_robots * time_remaining)
// If building one more robot each remaining turn:
max_possible += (time_remaining * (time_remaining - 1)) / 2
"Waiting is Never Optimal"
If you can build something now and you will build it later anyway, just build it now.
// Bad: Can build robot now, but wait and build same robot next turn
// Result: Same state but with fewer resources accumulated
// Good: Build now, get extra resource for free
This applies to any state-space search: if action A dominates action B (A is strictly better), skip B.
Common Bottlenecks
N+1 Queries
-- Bad: N+1 queries
for user in users:
orders = db.query("SELECT * FROM orders WHERE user_id = ?", user.id)
-- Good: Single query with JOIN
orders = db.query("SELECT * FROM orders WHERE user_id IN (?)", user_ids)
Unnecessary Allocations
# Bad: New list for each call
def get_names(users):
return [u.name for u in users]
# Good: Generator for large datasets
def get_names(users):
for u in users:
yield u.name
Inefficient Algorithms
- Nested loops: O(n²) → use Hash map
- Repeated sort: O(n log n) → sort once
- Linear search: O(n) → use Index/hash
Blocking Operations
- Synchronous I/O blocks thread
- Use async/await for I/O-bound work
- Batch database operations
Database Optimization
Indexing
- Index columns in WHERE and JOIN
- Composite indexes for multi-column queries
- Don't over-index (slows writes)
Query Patterns
-- Bad: Select all columns
SELECT * FROM users WHERE active = true
-- Good: Select only needed columns
SELECT id, name, email FROM users WHERE active = true
Connection Pooling
- Reuse database connections
- Configure pool size appropriately
Caching
When
- Frequently accessed data
- Expensive computations
- Rarely changing data
Strategies
- LRU: General purpose
- LFU: Frequently accessed
- TTL: Time-based
- Write-through: Write to cache + DB
- Write-back: Write to cache, async to DB
Remove Cache Last
Counterintuitive but practical: when state space shrinks enough, try removing the cache.
Rationale:
- Cache lookups have overhead (hash computation, memory access)
- As search space shrinks, duplicate states become rare
- Fewer states + no overhead can beat more states + hashmap lookups
Before: 12 million states, 48% cache hit rate → 417ms
After: 500k states, no cache → 24ms (17x faster)
Profile after removing cache. Sometimes less is more.
Profiling
Hot Path Analysis
For tight loops (thousands+ iterations):
- No memory allocation in loop
- No function call overhead in inner loop
- No unnecessary abstraction layers
- Data fits in cache (L1/L2)
- Invariant computations outside loop
Pre-Pass Pattern
// Bad: Work inside loop (called N times)
for point in &points {
let entities = world.gather_entities(point);
let mesh = find_mesh(&entities);
test_triangles(mesh, point);
}
// Good: Pre-pass (called once)
let entities = world.gather_all_entities();
let mesh = find_mesh(&entities);
for point in &points {
test_triangles(mesh, point);
}
Data Layout and Memory
Code is often 100x slower than hardware can handle. Memory bandwidth is often the bottleneck.
Memory Hierarchy
L1 Cache: ~32 KB, ~1 ns
L2 Cache: ~256 KB, ~4 ns
L3 Cache: ~8 MB, ~15 ns
RAM: ~GB, ~100 ns
SoA vs AoS
// Bad: Array of Structures (AoS) - cache-unfriendly
struct Particle {
position: Vector3,
velocity: Vector3,
color: Color,
mass: f32,
}
let particles: Vec<Particle> = Vec::new();
// Good: Structure of Arrays (SoA) - cache-friendly
struct ParticleSystem {
positions: Vec<Vector3>,
velocities: Vec<Vector3>,
colors: Vec<Color>,
masses: Vec<f32>,
}
Why: Moving data from RAM to CPU is the bottleneck. CPUs fetch 64 bytes at a time.
Smaller Types, Less Hashing
Smaller data types reduce memory bandwidth and hashing overhead:
// Hashmap key: 8 x u8 = 64 bytes to hash
struct Key { a: u8, b: u8, c: u8, d: u8, e: u8, f: u8, g: u8, h: u8 }
// Better: Pack into single u64 - one hash computation
#[repr(C)]
struct PackedKey(u64);
When hashing is a bottleneck:
- Use repr(C) so fields are contiguous in memory
- Pack into larger primitive types
- Fewer bytes = faster hashing
ECS Benefits
ECS naturally leads to cache-friendly layouts:
// Each component in its own array
let transforms: Vec<TransformComponent> = Vec::new();
let velocities: Vec<VelocityComponent> = Vec::new();
// Processing velocity only touches velocities array
Multi-Core By Default
Design for multi-core from the start, not as an afterthought.
Key Patterns
// Bootstrap: Launch all cores
fn bootstrap_entry_point() {
let thread_count = num_cores();
for thread_idx in 0..thread_count {
std::thread::spawn(move || {
entry_point(thread_idx, thread_count);
});
}
}
// Work distribution
fn entry_point(thread_idx: usize, thread_count: usize) {
let per_thread = values_count / thread_count;
let start = thread_idx * per_thread;
let end = start + per_thread;
for idx in start..end {
process(values[idx]);
}
}
// Go narrow (single-threaded) when needed
if thread_idx == 0 {
println!("Result: {}", sum);
}
Bucketing Mutations
Each thread should mutate separate memory regions:
// Good: Per-thread stack - never conflicts
fn thread_entry(thread_idx: usize) {
let mut x = 0; // Thread-local
for idx in 0..1000 {
x += idx;
}
}
// Bad: All threads write to same memory
static mut SHARED_COUNTER: u64 = 0;
Read-Only is Ideal
Best multi-threaded code:
- Reads shared data without sync
- Writes to thread-local or bucketed regions
- Syncs only at join points
Per-Thread Arenas
// Bad: Shared synchronized allocator
let data = malloc(size_of::<Data>());
// Good: Per-thread arenas - no synchronization
let arena = Arena::new();
let data = arena.alloc(size_of::<Data>());
Join Pattern
// Build separate tables in parallel, join at end
fn build_table_parallel(items: &[Item], thread_count: usize) -> Vec<Table> {
let tables: Vec<Table> = (0..thread_count).map(|_| Table::new()).collect();
for (idx, item) in items.iter().enumerate() {
tables[idx % thread_count].insert(&item.key, &item.value);
}
tables // Join: concatenate buckets
}
Striped Locking (Advanced)
For unavoidable shared access:
// One lock per bucket instead of one lock per table
struct StripedTable<T> {
buckets: Vec<Bucket<T>>,
locks: Vec<Mutex<()>>,
}
Back-of-Envelope Estimation
See napkin-math.md for detailed performance numbers and estimation techniques.
Quick Reference
Before optimizing, calculate achievable performance:
- Count actual operations (math ops, memory loads)
- Look up hardware limits (CPU GHz, FLOPS, cache bandwidth)
- Calculate theoretical minimum
If actual >> expected, look for:
- Unnecessary function calls in hot paths
- Memory allocation in loops
- Abstraction layers that don't optimize away
Example
50k raycasts × 30 triangle tests = 1.5M ops
CPU: 3 GHz × 8-wide SIMD = 24B ops/sec
Expected: ~0.06ms
Actual: 10,000ms → 100,000x overhead
→ Look for what's adding all that overhead
Abseil Performance Hints
Based on well-known performance hints.
The Importance of Thinking About Performance
The classic quote on premature optimization: "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%."
A 12% improvement is never considered marginal in engineering. Many make the mistake of ignoring performance during development, leading to:
- Flat profiles where performance is lost everywhere
- Hard to identify hotspots when everything is slow
- Library users who can't easily optimize
- Expensive solutions like over-replication
Suggestion: When writing code, choose the faster alternative if it doesn't impact readability/complexity significantly.
Estimation
Before choosing between options, do back-of-the-envelope calculations:
- Estimate low-level operations: disk seeks, network round-trips, bytes transmitted
- Multiply by rough costs and add up
- Discard alternatives that can't meet requirements
Measurement
Before making improvements, measure:
- Use profiling tools (pprof, perf)
- Write microbenchmarks for the code being improved
- Profile with hardware performance counters to find cache miss rates
What to Do When Profiles Are Flat
When there's no obvious hotspot:
- Don't discount many small optimizations (20 × 1% = significant)
- Find loops higher in call stacks
- Look for structural changes, not just micro-optimizations
- Replace overly general code with customized implementations
- Reduce allocations (often reduces allocator time AND cache misses)
API Design for Performance
Bulk APIs
Provide bulk operations to reduce expensive API boundary crossings:
// Bad: Per-item API
Status Lookup(const TensorIdProto& id);
// Good: Bulk API
bool LookupMany(absl::Span<const LookupKey> keys,
absl::Span<tensorflow::Tensor> tensors);
View Types
Prefer view types (string_view, Span, FunctionRef) for function arguments unless ownership is being transferred. This reduces copying and allows callers to use their own container types.
Pre-allocated/Pre-computed Arguments
For frequently called routines, allow callers to pass in already-available data:
// Instead of:
static void RecordRPC(const Name& name, const RPC_Stats_Measurement& m);
// Allow passing pre-computed value:
static void RecordRPC(const Name& name, const RPC_Stats_Measurement& m, WallTime now);
Thread-Compatible vs Thread-Safe Types
- Most types should be thread-compatible (synchronized externally)
- Callers who don't need thread-safety shouldn't pay for it
- If typical use needs synchronization, move it inside the type for flexibility
Algorithmic Improvements
The biggest performance wins come from algorithmic improvements:
- O(N²) → O(N log N) or O(N)
- Avoid exponential behavior
- Pre-compute instead of incremental building
Examples
- Reverse post-order graph initialization: Add entire graph at once instead of one edge at a time
- Better deadlock detection: O(|V|+|E|) space instead of O(|V|²)
- Hash table vs sorted intersection: O(N) instead of O(N log N)
- Proper hash functions: O(1) instead of O(N)
Better Memory Representation
Compact Data Structures
- Reorder fields to reduce padding
- Use smaller numeric types where data fits
- Use
enum class OpType : uint8_tinstead of full word enums - Place hot read-only fields away from hot mutable fields
Indices Instead of Pointers
On 64-bit machines, pointers are 64 bits. Use integer indices into arrays:
- Smaller references (32 bits if possible)
- Contiguous storage = better cache locality
Batched Storage
Avoid per-element allocations (std::map, std::unordered_map). Use flat representations:
- std::vector, flat_hash_map
- Chunked/flat storage = better cache behavior
Inlined Storage
For containers with typically small element counts:
absl::InlinedVector,absl::string_view- Avoids allocation when elements are few
Arenas
Pack independently allocated items together:
- Reduces allocation cost
- Better cache locality
- Eliminates destruction costs
- Beware: Don't put short-lived objects in long-lived arenas
Arrays Instead of Maps
If domain is small integer or enum, use arrays instead of maps:
// Bad
gtl::flat_map<int, int> payload_type_to_clock_frequency_;
// Good: Simple array
struct PayloadTypeToClockRateMap {
int map[128];
};
Bit Vectors Instead of Sets
If domain is small integer:
// Bad: hash set lookup
bool Contains(ZoneId zone) const { return count(zone) > 0; }
// Good: Bit vector
bool ContainsZone(ZoneId zone) const {
return zone < b_.size() && b_.get_bit(zone);
}
Reduce Allocations
Memory allocation adds costs:
- Time in allocator
- Initialization/destruction overhead
- Cache line fragmentation
Avoid Unnecessary Allocations
- Use static empty objects instead of creating new ones
- Use statically-allocated zero vectors when possible
Resize or Reserve Containers
When max size is known, pre-size the container:
// Bad: N push_back operations
for (int i = 0; i < ndocs-1; i++) {
docs_.push_back(...);
}
// Good: Pre-size
docs_.resize(ndocs);
DocId* docptr = &docs_[0];
for (int i = 0; i < ndocs-1; i++) {
*docptr = ...;
docptr++;
}
Avoid Copying
- Prefer moving to copying
- Store pointers/indices instead of copies
- Sort vectors of indices, not large objects
- Use std::sort instead of std::stable_sort
Reuse Temporary Objects
Hoist declarations outside loops:
// Bad: Recreated each iteration
for (...) {
std::vector<T> temp;
process(temp);
}
// Good: Reused
std::vector<T> temp;
for (...) {
temp.clear();
process(temp);
}
Algorithmica: HPC Techniques
Based on "Algorithms for Modern Hardware" (algorithmica.org).
Cache-Oblivious Algorithms
Cache-oblivious algorithms perform well across all cache levels without knowing the cache size:
// Cache-oblivious matrix transpose
fn transpose<T: Copy>(a: &[T], n: usize) -> Vec<T> {
let mut b = vec![a[0]; n * n];
for d in (1..n).step_by(2) {
for i in 0..n - d {
let j = i + d;
b[i * n + j] = a[j * n + i]; // Cache-friendly access
b[j * n + i] = a[i * n + j];
}
}
b
}
Key insight: Divide data to fit in cache, then recurse. Works at L1, L2, L3 automatically.
Compiler Optimization Flags
| Flag | Effect |
|---|---|
-O3 |
Aggressive optimization, vectorization |
-march=native |
Target build machine's CPU |
-ffast-math |
Relax floating-point precision (unsafe) |
-funroll-loops |
Unroll loops (sometimes hurts) |
Warning: -ffast-math breaks IEEE 754 compliance. Only use when precision
loss is acceptable.
Arithmetic Optimizations
Fast Inverse Square Root (Quake trick)
// Classic: ~3x faster than 1/sqrt(x) for gaming/graphics
fn fast_inv_sqrt(x: f32) -> f32 {
let i = x.to_bits();
let i = 0x5f375a86 - (i >> 1);
let y = f32::from_bits(i);
y * (1.5 - 0.5 * x * y * y) // Newton iteration
}
Integer Division by Constant
// Division by 3 - compile-time computed reciprocal
fn div_by_3(x: u64) -> u64 {
((x as u128 * 0x5555555555555555u64 as u128) >> 64) as u64
}
Case Studies from Algorithmica
| Optimization | Speedup |
|---|---|
| Binary search (SIMD) | 8-15x vs std::lower_bound |
| GCD (branchless) | 2x vs std::gcd |
| Prefix sum (SIMD) | 2-3x vs naive |
| Matrix multiplication (tiled + SIMD) | 100x vs for-for-for |
Memory Layout: AoS vs SoA
// Bad: Array of Structures (AoS) - cache unfriendly
struct Particle { x: f32, y: f32, vx: f32, vy: f32 }
let particles: Vec<Particle> = vec![];
// Good: Structure of Arrays (SoA) - cache friendly
struct Particles {
xs: Vec<f32>, ys: Vec<f32>, vxs: Vec<f32>, vys: Vec<f32>
}
Prefetching
// Manual prefetch for accessing pattern
for i in 0..n {
if i + 16 < n {
// Prefetch 16 iterations ahead
prefetch(&data[i + 16]);
}
process(data[i]);
}
Note: Hardware prefetchers are usually better. Only use manual prefetch when access pattern is complex.
Language-Specific Optimization
For language-specific performance techniques, see:
- performance-rust.md - Rust optimization
- performance-zig.md - Zig optimization
- performance-go.md - Go optimization
- performance-java.md - Java optimization
- performance-c.md - C optimization
- performance-asm.md - Assembly optimization
- performance-simd.md - SIMD optimization
- performance-gpu.md - GPU optimization
- performance-parallel.md - Parallelization
Use this skill before major performance optimization work.