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

后端 未结 5 1627
渐次进展
渐次进展 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 17:47

    The answers here are good, though I had an idea that might improve things.

    Since the two branches and associated branch prediction are the likely culprit, we may be able to reduce the branching to a single branch without changing the logic at all.

    bool aNotZero = (nums[0][i] != 0);
    bool bNotZero = (nums[1][i] != 0);
    if (aNotZero && bNotZero) { /* Some code */ }
    

    It may also work to do

    int a = nums[0][i];
    int b = nums[1][i];
    if (a != 0 && b != 0) { /* Some code */ }
    

    The reason being, by the rules of short circuiting, if the first boolean is false, the second should not be evaluated. It has to perform an extra branch to avoid evaluating nums[1][i] if nums[0][i] was false. Now, you may not care that nums[1][i] gets evaluated, but the compiler can't be certain that it won't throw an out of range or null ref when you do. By reducing the if block to simple bools, the compiler may be smart enough to realize that evaluating the second boolean unnecessarily won't have negative side effects.

提交回复
热议问题