Pae*_*dow -1 java performance if-statement
使用条件/三元运算符:
freeCache = (freeCache > (2880 * 3)) ? (2880 * 3) : freeCache;
Run Code Online (Sandbox Code Playgroud)
在每种情况下都有一个值赋值.
使用这个正常的if语句:
if(this.freeCache > (2880 * 3)) this.freeCache = (2880 * 3)
Run Code Online (Sandbox Code Playgroud)
如果freeCache值太高,应该只有一个值赋值.
那么哪一个实际上更有效?
只是为了它的乐趣,我尝试编译两个建议的实现(三元运算符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
Run Code Online (Sandbox Code Playgroud)
用'?' 三元运算符:
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
Run Code Online (Sandbox Code Playgroud)
?由于该:条款(上面列出的标记为15和16的说明),使用运算符(至少在这种特定情况下)效率很低.JVM可能会优化这些冗余操作.