Which of the following is better in terms of performance and efficient memory usage?
Boolean isItTrue(arg){
return Boolean.TRUE;
}
boolean isItTrue(arg){
return Boolean.TRUE
}
Boolean isItTrue(arg){
return true;
}
boolean isItTrue(arg){
return true;
}
It should be faster and easier to work with primitive types, but on the other hand, when using a reference to a static object, no new value is created. Or is it optimized on compiler level and all true
and false
are replaced by references to the static objects to save memory?
If there is any performance gain it is so minuscule as to be irrelevant. Boolean.TRUE and Boolean.FALSE don't return a new object in any case.
Favour clarity for the code maintainer over such micro-optimisations. The question should not be "which is smaller/faster", first which expresses what you mean.
If the method returns a Boolean object then whoever receives needs to decide whether there is a possibility that it might be null, and that if it is null that it might mean something different from true/false, like "we don't know".
So return type of boolean, if that is what you mean, otherwise, if you want to allow Null, then Boolean.
If returning a boolean then
must be better than relying on autoboxing, again for the sake of clarity as well as performance.
If returning Boolean then
must be good, it just avoids creating extra garbage, much as I oppose micro-optimisation I see no value in being wilfully inefficient. I'd argue that it's also clearer in that you are conspicuously matching the return type.
java.lang.Boolean takes 16 bytes.
this is the way to go if you are only looking for performance and memory size issues:
The last one
I use
Boolean
only if the method needs sometimes to returnnull
By that logic, the reference to the static object itself is as costly as the truth value, if not more.
Using objects may be somewhat slower than primitives, but I wouldn't worry: the difference is irrelevant.
Use the last one (just
boolean
). Even if the compiler optimizes them all to the same thing, at the very least you're making the compiler's job easier (it's not an easy job you know!).Plus it's fewer keystrokes (don't need to press shift). But really, the only reason you should use the wrapper class is when you need the ability to set it to
null
, and for use in generic data structures likeLinkedList<E>
.