Which of these pieces of code is faster in Java

十年热恋 提交于 2020-01-06 23:20:11

问题


I was wondering which piece of code is going to run faster since I want to optimize as much as possible.

code A:

if(((a & 0x0FFF) + (b & 0x0FFF)) & 0x1000 != 0)
{
    Register.setHCarryFlag(true);
}
else
{
    Register.setHCarryFlag(false);
}

code B:

Register.setHCarryFlag(((a & 0x0FFF) + (b & 0x0FFF))& 0x1000 != 0);

The reason I ask is I suspect that code B doesn't branch, but I don't know for sure how each is converted to machine code.

Better yet, is there a way to see the machine code that is produced from each piece of code?


回答1:


However you turn it, you'll be safer with the second approach because there is fundamentally no branching there, just pure calculation. A good JIT compiler may recognize that your branch in the first example can be eliminated, but why make it more difficult for JIT—and for a human reader.




回答2:


if(__CONDITION_TRUE_?_) 
{
    return true;
} 
else 
{
    return false;
} 

should always be written as

return __CONDITION_TRUE_?_;


来源:https://stackoverflow.com/questions/32294880/which-of-these-pieces-of-code-is-faster-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!