Asdfasf

Thursday, August 21, 2014

EJ-5 Avoid Creating Unnecessary Object

Ref: Effective Java by Joshua Bloch

In Item-5 of Effctive Java, Mr Bloch expresses that avoid creating unnecessary object. In essence, this requires knowing your tool, Java.

String s = new String("test"); //DON'T DO THIS

The statement creates a new String instance each time it is executed. The improved version is simply the following:

String s = "test";

This version uses a single String instance, rathe rthan creating new one each time it is executed. This idiom is called String Interning.
Here is a really interesting sample code demonstrating String interning.



First checkEquality results that both two strings are exatly same instance with same identity code and both == and equals() give true.
Second checkEquality results that two strings are different instances created with different identity codes and == results false but equals() results true.

396857438
396857438
true
true
2046236531
1294253459
true
false

Mr Bloch advices to avoid unnecessary objects by using static factory methods in preference to constructors on immutable classes. If a class preferable immutable, why you should create new instance each time instead of creating one and using it.

Boolean.valueOf(String) is almost always preferable to the constructor Boolean(String)

Boolean.TRUE is implemented inside Boolean class as a static final Boolean element:

public static final Boolean TRUE = new Boolean(true);

No comments: