In PHP, there are at least four ways of checking if a given variable is in the set {0, 1}, or not:
($ var > -1 && $ var < 2)
($ var >= 0 && $ var <= 1)
($ var == 0 || $ var == 1)
!($ var < 0 || $ var > 1)
At first look, it would appear that either the first expression is most efficient, or the first two are equally efficient, depending on whether or not a >=
OR <=
comparison takes more operations than a >
OR <
comparison. This is because the compiler/interpreter can stop processing the expression at &&
if the first part is false.
I would imagine that after the first two, the next most efficient would be the third, closely followed by the fourth as least efficient because of the added !
operator at the beginning of the expression.
Is my assessment correct in PHP, and considering I made my judgement based on machine operations independent of language, would the same hold true across other languages?