Java performance: true vs. Boolean.TRUE

2020-02-08 02:29发布

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?

9条回答
虎瘦雄心在
2楼-- · 2020-02-08 03:00

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.

查看更多
Rolldiameter
3楼-- · 2020-02-08 03:00

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

return true; // or false

must be better than relying on autoboxing, again for the sake of clarity as well as performance.

If returning Boolean then

return Boolean.TRUE

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.

查看更多
时光不老,我们不散
4楼-- · 2020-02-08 03:01

java.lang.Boolean takes 16 bytes.

this is the way to go if you are only looking for performance and memory size issues:

boolean isItTrue(arg){
    return true;
}
查看更多
老娘就宠你
5楼-- · 2020-02-08 03:04

The last one

boolean isItTrue(arg){
    return true;
}

I use Boolean only if the method needs sometimes to return null

查看更多
ゆ 、 Hurt°
6楼-- · 2020-02-08 03:05

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.

查看更多
爷的心禁止访问
7楼-- · 2020-02-08 03:07

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 like LinkedList<E>.

查看更多
登录 后发表回答