使用三元运算符的缺点 [英] Disadvantages of using ternary operator

查看:784
本文介绍了使用三元运算符的缺点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的源代码中有以下版本

I have the following statments in my source code

int tableField1;
int tableField2;

int propertyField1;
int propertyField2;

if (tableField1 != null)
{
  propertyField1 = tableField1;
}

if (tableField2 != null)
{
  propertyField2 = tableField1;
}

// the above pattern is repeated for 10 tablefields ie tableField3, tableField4... tableField10

我使用三元运算符减少了上面的计算,如下:

I reduced the above statments using the ternary operator as follows

propertyField1 = tableField1 != null ? tableField1 : propertyField1;
propertyField2 = tableField2 != null ? tableField2 : propertyField2;

以下是我的问题:

1 )三元运算符比if语句使用效率低。

1) Is ternary operator inefficient to use than the if statements.

2)使用三元运算符有什么缺点(如果有)。

2) What are the disadvantages (if any) to use ternary operator.

推荐答案

为什么不使用null合并运算符?

Why not use the null coalescing operator instead?

propertyField1 = tableField1 ?? propertyField1;

不可否认,它看起来稍微 odd将原始值分配回同一个变量中。它可能会比 if 语句稍微低一些的效率,因为在理论上你正在读取的值并重新赋值...但我不会如果JIT省略了,就会感到惊讶。无论如何,这肯定是在微优化的水平。

Admittedly it looks slightly odd assigning the original value back to the same variable. It's possible that it'll be very slightly less efficient than the if statements, as in theory you're reading the value and assigning it again... but I wouldn't be surprised if the JIT elided that. Anyway, that's definitely at the level of micro-optimization.

有些人认为条件运算符是不好的可读性 - 我一般认为这是简单的语句,虽然 有点模糊了只有改变价值,如果我们有一个新的的意义。

Some people consider the conditional operator to be bad for readability - I generally think it's fine for simple statements like this, although it is somewhat obscuring the meaning of "only change the value if we've got a new one".

这篇关于使用三元运算符的缺点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆