Java ternary compared with large objects

Ternary operators are usually just a topic of philosophical discussion:

a=b>5?1:0;

More readable, faster, cooler

if(b>5) { a=1; } else {a=0;}

(with or without curly braces) I usually don't care I like my ternary operator But we discussed this Code:

BigObject myBigObject=null;
...
do {
   myBigObject=
     myBigObject==null?
     createBigObject():
     myBigObject;
...
} while(manyIteration);

My colleague claimed that this construct will create mybigobject and will be copied every loop (except the first one), which will waste valuable time and memory, and he found that the ternary operator is useless The only way is:

do {
     if(myBigObject==null)
       myBigObject=createBigObject();
...
} while(manyIteration);

I think a smart compiler will see objects assigned to itself and optimize them

But who's right?

Solution

The clear answer lies in JLS section 15.25 (emphasize my):

This means that two expressions are not always evaluated: only that expression is needed In fact, all of you are right

>You are wrong because the compiler is not smart: it is specified by the language itself; > Your colleague is wrong because the expression will not be evaluated if it is not needed

In code

myBigObject = myBigObject == null ? createBigObject() : myBigObject;
              ^-----------------^   ^---------------^             
           this is true the 1st time,hence that ^ is evaluated


myBigObject = myBigObject == null ?    createBigObject()     :        myBigObject;
              ^-----------------^                              
           this is false the 2nd time,hence that ^ is NOT evaluated,that ^ is

Note that all you do is assign mybigobject to yourself, not create a new object

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>