Performance Optimization
performance optimization measure, don't guess. java performance work without a profiler is folklore. once you measure, the wins are usually in algorithms,
Introduction
Measure, don't guess. Java performance work without a profiler is folklore. Once you measure, the wins are usually in algorithms, allocation rate, and I/O — rarely in micro-tweaks.
Understanding the topic
The 80/20 of JVM perf wins:
- Right-size heap; pick a GC (
ZGCfor latency). - Eliminate N+1 DB queries — most 'slow Java' is actually slow SQL.
- Use connection pools (
HikariCP); set sane timeouts everywhere. - Cache hot reads with Caffeine (size + TTL bounds, not unbounded).
- Avoid auto-boxing in tight loops (prefer
int[]overList<Integer>). - Use virtual threads for blocking I/O instead of growing thread pools.
Real-world use
War story: a checkout API hit 99p latency of 1.2s. JFR showed 70% of time in String.format inside the logger — every request logged a debug line at INFO level. Lowering the log level cut p99 to 80ms. Nothing about the business logic changed.
Best practices
- Profile in production with JFR — overhead is < 1%.
- Use async-profiler for CPU flame graphs.
- Benchmark with JMH, not
System.nanoTimein a loop.
Purpose of this lesson
Master Performance Optimization so you can apply it confidently in production Java code, technical interviews, and code reviews.
Step-by-step explanation
- Understand the core idea behind Performance Optimization.
- Walk through the runnable example and tweak it in the playground.
- Apply the pattern in a small Spring Boot or CLI exercise of your own.
- Re-read the common mistakes and interview Q&A to lock the concept in.
Interactive workflow diagram
Identify use case
Recognize when performance optimization is the right tool for the problem.
Debugging tips
- Read the full stack trace — Java's exception messages name the offending class and line.
- Reproduce in the smallest possible
main()method before fixing in the real app. - Use IntelliJ's debugger breakpoints and 'Evaluate Expression' rather than scattering
System.out.
Optimization strategies
- Measure with JMH for micro-benchmarks — never trust
System.currentTimeMillis()loops. - Reduce allocation: reuse buffers, prefer primitives, watch boxing in hot paths.
- Cache wisely: Caffeine for in-process, Redis for shared.
Enterprise example
Teams at Netflix, Uber and Goldman Sachs apply Performance Optimization daily — usually wrapped behind Spring Boot services with observability hooks (Micrometer + OpenTelemetry).
Interview questions & answers
Q1Explain Performance Optimization in one minute.
Q2When would you avoid Performance Optimization?
Summary
In this lesson you learned Performance Optimization — the concept, syntax, a runnable example, and the production pitfalls to avoid. Apply it in the playground before moving on.