Why is (a*b != 0) faster than (a != 0 && b != 0) in Java?

后端 未结 5 1625
渐次进展
渐次进展 2021-01-29 17:34

I\'m writing some code in Java where, at some point, the flow of the program is determined by whether two int variables, "a" and "b", are non-zero (note: a a

5条回答
  •  温柔的废话
    2021-01-29 18:07

    You are using randomized input data which makes the branches unpredictable. In practice branches are often (~90%) predictable so in real code the branchful code is likely to be faster.

    That said. I don't see how a*b != 0 can be faster than (a|b) != 0. Generally integer multiplication is more expensive than a bitwise OR. But things like this occasionally get weird. See for example the "Example 7: Hardware complexities" example from Gallery of Processor Cache Effects.

提交回复
热议问题