Avoid Creating Unnecessary Objects

Avoid Creating Unnecessary Objects

This item sounds simple, yet performance loss often starts here.

Classic Mistake: Redundant Allocation
String s = new String("Java Best Practices!"); // avoid        
Better form:
String s = "Java Best Practices!";        

What changes:

  • First version allocates a new heap object every execution.
  • Second version reuses a single interned instance from the string pool.

Inside a loop running one million iterations, the first version produces one million unused objects and extra GC pressure.

Hidden Cost: Autoboxing

Object creation hides behind syntax.

Long sum = 0L;
for (long i = 0; i < Integer.MAX_VALUE; i++) {
    sum += i;
}        

sum uses Long while i uses primitive long.

Each iteration triggers:

  • Unboxing sum to long
  • Addition
  • Boxing result into a new Long

Result: billions of temporary objects under load.

Correct form:
long sum = 0L;
for (long i = 0; i < Integer.MAX_VALUE; i++) {
    sum += i;
}        

No boxing. No allocation. Stable throughput.

Example

Pricing engines loop through millions of cash flows.

Using Double instead of double inside valuation loops forces allocation on every step. GC pauses increase latency during market open. Primitive arithmetic keeps valuation pipelines stable under volume spikes.

Eliminate Obsolete Object References

Garbage collection does not prevent memory leaks.

Leak definition: objects stay reachable even though no logic needs them.

Common sources:

  • Static collections growing forever
  • Caches without eviction
  • Listeners never removed
  • Maps keyed by long lived objects

Example pattern:
private static final List<Order> ORDERS = new ArrayList<>();        

Orders added during trading day remain reachable after settlement unless removed.

GC sees references. GC keeps memory.

Example

Order management systems accumulate millions of trade objects per session.

Without eviction, heap usage rises until latency spikes or OutOfMemoryError hits during peak execution windows.

Production outages follow, not due to math, but due to stale references.

Rules of Thumb

  • Prefer primitives in hot paths
  • Avoid wrapper types inside loops
  • Reuse immutable objects
  • Clear collections once data loses relevance
  • Treat caches with eviction policy


Takeaway

Performance issues start with allocation habits. GC removes unreachable memory, not unnecessary memory. Design and discipline decide which objects deserve space in the heap.

To view or add a comment, sign in

More articles by Ankur Mistry

  • Lambdas, Method References, Streams

    Prefer Lambdas to Anonymous Classes Before Java 8: With lambdas: Shorter. Clearer.

  • Generics in Java

    Generics replace runtime failure with compile time guarantees. Before Java 5, casts hid defects until production…

  • Prefer Interfaces to Abstract Classes

    Java supports single inheritance. Extending an abstract class consumes the only superclass slot.

  • Inheritance vs Composition in Java

    Object reuse looks simple: extend a class and gain behavior. In production systems, inheritance creates long term risk…

  • Control Access to Protect Design

    Encapsulation drives decoupling. Once access spreads, refactoring cost rises across teams and systems.

  • Methods Common to All Objects

    Obey the General Contract When Overriding equals Overriding equals looks simple: check whether two objects match. In…

  • Avoid Finalizers and Cleaners

    Never rely on object finalization for resource management. In C++, destructors run at deterministic points.

  • Prefer Dependency Injection to Hardwiring Resources

    A design rule many engineers follow instinctively, yet often violate under time pressure. Problem: Hardwired…

  • Enforce Noninstantiability

    Some classes exist only as containers for static methods and constants. Examples from the JDK: These classes represent…

  • Singleton Instance

    Enforcing a Single Instance with the Singleton Property After covering factories and builders, object creation control…

Explore content categories