Performance Optimization & Profiling
Prerequisites: Testing strategies
Measure before optimizing — a profiler (like the one built into
IntelliJ, or async-profiler) shows exactly where a running program
actually spends its time and memory, rather than guessing.
Common, high-value fixes once a real bottleneck is found:
- Choosing the right collection — a
HashMaplookup is O(1), a linear search through aListis O(n); using the wrong one at scale is a frequent, easy-to-fix bottleneck. - Avoiding unnecessary object creation inside a hot loop (e.g.
Stringconcatenation with+instead ofStringBuilder, revisited from Level 1 now at scale). - Batching database calls instead of issuing one query per item in a loop (the classic "N+1 query" problem).
Common mistakes
- "Optimizing" code that isn't actually a bottleneck, based on a guess rather than a profiler's measurements — this often makes the code harder to read for no measurable benefit.