使用条件/三元运算符:
freeCache = (freeCache > (2880 * 3)) ? (2880 * 3) : freeCache;
在每种情况下都有一个值赋值。
使用这个正常的if语句:
if(this.freeCache > (2880 * 3)) this.freeCache = (2880 * 3)
如果freeCache值太高,则只应该赋值。
那么哪一个实际上更有效?
答案 0 :(得分:5)
只是为了它的乐趣,我尝试编译两个建议的实现(三元运算符vs显式if语句)。他们都使用if_icmple
指令,所以我猜性能将是相同的:
if
版本:
public static void main(java.lang.String[]);
Code:
0: iconst_0
1: istore_1
2: iload_1
3: sipush 8640
6: if_icmple 13
9: sipush 8640
12: istore_1
13: return
使用'?'三元运算符:
public static void main(java.lang.String[]);
Code:
0: iconst_0
1: istore_1
2: iload_1
3: sipush 8640
6: if_icmple 15
9: sipush 8640
12: goto 16
15: iload_1
16: istore_1
17: return
由于?
子句(上面列表中标记为15和16的说明),使用:
运算符(至少在此特定情况下)存在轻微的低效率。 JVM可能会优化这些冗余操作。
答案 1 :(得分:2)
他们甚至没有等同于。
三元表达式可以扩展到:
if(freeCache > (2880 * 3)) {
freeCache = 2880 * 3;
} else {
freeCache = freeCache;
}
如果您真的关心性能,那么您的性能会受到影响,因为您再次执行冗余分配。
在所有情况下,您都应该努力提高可读性首先。单if
语句可能是更好的选择,因为它比您复杂的三元表达式更具可读性。