Reduce object creation in performance-critical paths by carefully evaluating allocation patterns. For frequently instantiated objects, consider caching instances or using static helpers, but always validate improvements with proper benchmarks.
Reduce object creation in performance-critical paths by carefully evaluating allocation patterns. For frequently instantiated objects, consider caching instances or using static helpers, but always validate improvements with proper benchmarks.
Key practices:
new HashMap<>(expectedSize * 4/3 + 1)
Example of object creation optimization with benchmark validation:
// Before: Creates new factory for every request
public URI getUrl() {
final DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory();
factory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.URI_COMPONENT);
return factory.expand(uriTemplate.toString(), uriVariables);
}
// After: Uses static factory instance
private static final DefaultUriBuilderFactory URI_BUILDER_FACTORY;
static {
URI_BUILDER_FACTORY = new DefaultUriBuilderFactory();
URI_BUILDER_FACTORY.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.URI_COMPONENT);
}
public URI getUrl() {
return URI_BUILDER_FACTORY.expand(uriTemplate.toString(), uriVariables);
}
Always verify optimizations with JMH benchmarks that prevent dead-code elimination:
@Benchmark
public Object measureOptimizedCode(Blackhole blackhole) {
Object result = optimizedOperation();
blackhole.consume(result); // Prevent JVM optimization from removing code
return result;
}
Enter the URL of a public GitHub repository