加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java三元与大对象相比

发布时间:2020-12-15 04:47:39 所属栏目:Java 来源:网络整理
导读:三元运算符通常只是一个哲学讨论的主题: 是否 a=b5?1:0; 更可读,更快,更酷 if(b5) { a=1; } else {a=0;} (带或不带花括号)我通常不在乎.我喜欢我的三元运算符.但我们讨论了这段代码: BigObject myBigObject=null;...do { myBigObject= myBigObject==null?
三元运算符通常只是一个哲学讨论的主题:
是否

a=b>5?1:0;

更可读,更快,更酷

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

(带或不带花括号)我通常不在乎.我喜欢我的三元运算符.但我们讨论了这段代码:

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

同事声称这个构造将创建myBigObject将被复制每个循环(除了第一个),这将浪费宝贵的时间和内存
并且他发现了三元运算符无用的情况.唯一的方法是:

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

我认为聪明的编译器会看到对象被分配给自己并将其优化出来.

但谁是对的?

解决方法

明确的答案在于JLS的 section 15.25(强调我的):

The resulting boolean value is then used to choose either the second or the third operand expression:
– If the value of the first operand is true,then the second operand expression is chosen.
– If the value of the first operand is false,then the third operand expression is chosen.

The chosen operand expression is then evaluated and the resulting value is converted to the type of the conditional expression as determined by the rules stated below.

This conversion may include boxing or unboxing conversion (§5.1.7,§5.1.8).

The operand expression not chosen is not evaluated for that particular evaluation of the conditional expression.

这意味着并不总是评估两个表达式:只需要那个表达式.实际上,你们谁都是对的.

>你错了,因为编译器并不聪明:它是由语言本身指定的;
>你的同事是错的,因为如果不需要,表达式将不会被评估.

在代码中

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

请注意,执行的只是将myBigObject分配给自身,而不会创建新对象.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读