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 sumin 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)
// ~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.
| Area | Habit |
|---|---|
| Strings | builder + presize; avoid += in loops; equals, never == |
| Boxing | primitives in loops/fields; primitive streams; watch Map<Integer,…> hot keys |
| Collections | presize; right structure; iterate entrySet, not keySet+get |
| Regex/formatters | compile once as static final |
| Exceptions | never for control flow; consider fillInStackTrace cost |
| Logging | parameterized messages; guard expensive args (Logging) |
| I/O | buffer everything; batch syscalls (Io Streams) |
| Methods | small and monomorphic-friendly for inlining |