Reputation: 1803
PMD is warning me to avoid Boolean instantiation (for efficiency reasons). I have something like this
Boolean variable = new Boolean(somestringIGotRepresentingABoolean);
And I'm supposed to use this
Boolean variable = Boolean.valueOf(somestringIGotRepresentingABoolean);
Why is that better?
Upvotes: 9
Views: 4470
Reputation: 51353
The reason is that new Boolean always returns a new instance. Since Boolean instances are immutable it does not make sense to have more than 2 instances. One for false and one for true.
Try this and you will see
Boolean boolean1 = new Boolean("true");
Boolean boolean2 = new Boolean("true");
Boolean boolean3 = new Boolean("true");
System.out.println(System.identityHashCode(boolean1));
System.out.println(System.identityHashCode(boolean2));
System.out.println(System.identityHashCode(boolean3));
Boolean valueOf1 = Boolean.valueOf("true");
Boolean valueOf2 = Boolean.valueOf("true");
System.out.println(System.identityHashCode(valueOf1));
System.out.println(System.identityHashCode(valueOf2));
Upvotes: 14
Reputation: 6276
In Java Boolean (like String) is immutable. That means if you use
Boolean x = new Boolean(true);
x = false;
x will point to a different Object after the "x = false" than it did before. So if you use the Boolean.valueOf() method Java will take care that there are only two Boolean objects at max, one representing true and the other representing false. If you use .valueOf(true) it will return a handle to the true-object and if you use .valueOf(false) it will return a handle to the false-object. Thus you don't create any unnecessary objects and thus they won't have to be deleted by the garbage collector.
If you use "new Boolean()" instead this doesn't work and Java will create a new Object every time. Thus you will have a ton of unnecessary objects that will probably be freed quite quickly and have to be cleaned by the garbage collector. So this costs you more memory (for all the objects), time for the allocation (when creating new Booleans) and time for the deallocation (when the objects are caught by the garbage collector), while giving you no advantages at all.
Upvotes: 4
Reputation: 5233
From the documentation, you can read:
new Boolean(boolean value)
Allocates a Boolean object representing the value argument.
Note: It is rarely appropriate to use this constructor. Unless a new instance is required, the static factory valueOf(boolean) is generally a better choice. It is likely to yield significantly better space and time performance.
Upvotes: 9