Describe a time you had to optimize slow Java code. What was your approach?
Quick Answer
A strong answer follows: measure first (profiler or targeted benchmarks) rather than guessing where time goes, identify the actual bottleneck (often an N+1 query, an inefficient collection choice, excessive object allocation, or a lock contention point rather than 'Java being slow'), make a targeted change, and re-measure to confirm the fix actually helped before and after — since intuition about performance is frequently wrong.
Detailed Answer
This is a classic behavioral question probing whether you optimize systematically or just guess. A strong answer walks through a concrete example using this structure:
-
Measure before optimizing. Use a profiler (async-profiler, JFR/Java Flight Recorder, VisualVM) or targeted micro-benchmarks (JMH for method-level comparisons) to find where time is actually being spent — intuition about "what's slow" in a large codebase is frequently wrong, and optimizing the wrong part wastes effort while leaving the real bottleneck untouched.
-
Identify the actual bottleneck category, which in Java code is very often one of:
- An N+1 query pattern (looping over results and issuing a query per iteration instead of one batched query).
- A collection/algorithm mismatch (e.g., using
contains()on aListin a hot loop — O(n) each call — instead of aHashSet/HashMapfor O(1) lookups). - Excessive object allocation in a hot path, generating unnecessary GC pressure (e.g., string concatenation with
+inside a loop instead ofStringBuilder, or unnecessary boxing of primitives). - Lock contention — a coarse-grained lock serializing work that could be parallelized or made lock-free.
-
Make a targeted, minimal change addressing that specific bottleneck rather than a broad rewrite, to keep risk low and the before/after comparison clean.
-
Re-measure with the same tool/benchmark used in step 1, to confirm the change actually improved the metric that mattered (latency, throughput, memory) — and check for regressions elsewhere.
What interviewers listen for: a methodical measure → hypothesize → fix → re-measure loop, concrete numbers (e.g., "cut p99 latency from 800ms to 120ms"), and awareness that the biggest wins are usually algorithmic/structural rather than micro-level JVM tuning.