Search code examples
c++returnreturn-value

Which conditional statement is faster than the other (width*height*depth == 0) OR (width ==0 || height == 0 || depth == 0)


When describing 3-dimensional objects in an algorithm where computation speed is important, which of the following conditional expressions is faster?

class Box {
    unsigned int width, height, depth;

public:
    bool isNull(){

       return (width*height*depth == 0);
       //OR
       return (width ==0 ||  height == 0 || depth == 0);
    }
};

Solution

  • It depends on your compiler, you can check compiled assembly for both of them and compare. You can as well time 2 options. Second one looks much better though. Note that if any of the values will be non-zero, rest will short circuit and will not be executed. Be sure to put the one that has the highest probability of being non-zero to the front. i.e. (highestProb == 0 || secondHighest == 0 || leastProb == 0)