gpt4 book ai didi

Java Ternary vs. 如果有大对象

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:37:56 24 4
gpt4 key购买 nike

三元运算符通常只是哲学讨论的主题:是否

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);

我认为聪明的编译器会看到对象被分配给它自己并优化它。

但谁是对的?

最佳答案

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

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 分配给它自己,而不会创建新对象。

关于Java Ternary vs. 如果有大对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35769203/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com