Performance & Optimization

Language-Level Performance

The code-level catalog, applied after profiling: allocation discipline in hot paths, string handling, boxing, collection sizing and choice, exception cost, and the JIT-friendliness of small monomorphic methods.
  • Avoid creating unnecessary objects in hot paths (EJ 6) — elsewhere, clarity wins
  • String concat in loops → StringBuilder, presized when possible (EJ 63)
  • Boxing in hot loops: Long sum in a loop creates millions of objects (EJ 61)
  • Presize collections; choose by access pattern (Choosing Collections)
  • Exceptions are for exceptional paths — construction cost is the stack trace
  • Small, focused methods inline; megamorphic call sites don't (Jit Compilation)
The EJ Item 6/61 classic
// ~6 seconds: creates 2^31 Long objects
Long sum = 0L;
for (long i = 0; i < Integer.MAX_VALUE; i++) sum += i;

// ~0.6 seconds: one variable
long sum2 = 0L;
for (long i = 0; i < Integer.MAX_VALUE; i++) sum2 += i;

// Compile-once regex (String.matches recompiles per call):
private static final Pattern ROMAN = Pattern.compile("^(?=.)M*(C[MD]|D?C{0,3})...");
boolean isRoman(String s) { return ROMAN.matcher(s).matches(); }

Allocation nuance the books insist on: small short-lived objects are nearly free (TLAB + young GC), and escape analysis deletes many entirely — so "avoid objects" as a blanket style produces obfuscated code with no payoff (EJ 6 explicitly warns against your own object pools for lightweight objects). The wins live in hot paths found by profiling: per-request buffers reused, streams-of-boxes turned into primitive streams, format/parse objects (DateTimeFormatter, Pattern) hoisted to constants.

Hot-path checklist (distilled from Optimizing Java ch. 11 & Java Secrets)
AreaHabit
Stringsbuilder + presize; avoid += in loops; equals, never ==
Boxingprimitives in loops/fields; primitive streams; watch Map<Integer,…> hot keys
Collectionspresize; right structure; iterate entrySet, not keySet+get
Regex/formatterscompile once as static final
Exceptionsnever for control flow; consider fillInStackTrace cost
Loggingparameterized messages; guard expensive args (Logging)
I/Obuffer everything; batch syscalls (Io Streams)
Methodssmall and monomorphic-friendly for inlining
Sources
  • Effective Java (3rd ed.)Items 6, 61, 63, 67
  • Optimizing JavaCh. 11 — Java Language Performance Techniques
  • Java Secrets: High Performance and ScalabilityPerformance techniques chapters