问题
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