我的源代码中有以下语句
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
我使用三元运算符将上述语句简化如下
propertyField1 = tableField1 != null ? tableField1 : propertyField1;
propertyField2 = tableField2 != null ? tableField2 : propertyField2;
以下是我的问题:
1)三元运算符的使用效率是否比 if 语句低。
2)使用三元运算符有哪些缺点(如果有)?
为什么不使用空合并运算符呢?
propertyField1 = tableField1 ?? propertyField1;
不可否认它看起来slightly奇数将原始值分配回同一个变量。它的效率可能会比if
语句,理论上你正在读取值并再次分配它......但如果 JIT 忽略了这一点,我不会感到惊讶。无论如何,这绝对是微观优化的水平。
有些人认为条件运算符不利于可读性 - 我通常认为对于像这样的简单语句来说很好,尽管它is有点模糊了“只有在我们有了新值时才更改值”的含义。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)