In terms of speed, which is fastest and why ?
x&1 //checks last bit
or
x%2 // performs modulo operation
In terms of speed, which is fastest and why ?
x&1 //checks last bit
or
x%2 // performs modulo operation
Under the as-if rule, if the two results have the same effect, a compiler is free to substitute one with another.
Only insofar as they give different results can one be said to be more optimal than the other.
In this case, negative numbers (may?) return a negative result under x%2
, and x&1
may be undefined for many integer values (or at least implementation defined).
However if they are well defined (based on 2s complement representation of signed integers say), and you then evaluate an if
condition on them, then they once again become equivalent, in which case the compiler is free to replace one with the other, and neither is faster than the other.