[Effective Java] Item 6 – Avoid creating unnecessary objects

Published by

on

1. Reuse objects

  • Rather than creating new objects that does the same job every time, reuse the single object by using static factory methods or immutable object.
    • For example, use Boolean.valueOf(String) which is a static factory method rather than Boolean(String).
    • Immutable objects like String can be reused any time. For example, use String s = "bikini"; rather than String s = new String("bikini");
  • Reuse the expensive object by caching
    • String.matches() can degrade the performance as it uses Pattern instance just once and discards it which leaves it to the GC.
    • To improve the performance, create the Pattern instance from the class instantiating level by declaring it as static, and reuse whenever it’s required.

2. Adapter pattern

  • Adapter is an object that delegates to a backing object, providing an alternative interface
    • keySet() of Map interface returns a Set view of the Map object, which returns the same Set instance per every call.

3. Prefer primitives to boxed primitives

  • sum += i; would create Long instance every time. Changing the sum type from Long to long improves the performance much better.
  • Long sum, long i =>
  • long sum, long i =>
  • Long sum , Long i =>

Check List

1. What is the difference between primitive type and boxed primitive type ?

  • To Be Updated

2. Why is String type immutable ?

Reference

Leave a comment