The following pieces of code do the same logic (x is either 0 or 1 only). Which code executes faster ?
First Code:
if (x == 1)
{
y = 10;
}
Second Code:
if (x != 0)
{
y = 10;
}
Third Code:
if (x)
{
y = 10;
}
The following pieces of code do the same logic (x is either 0 or 1 only). Which code executes faster ?
First Code:
if (x == 1)
{
y = 10;
}
Second Code:
if (x != 0)
{
y = 10;
}
Third Code:
if (x)
{
y = 10;
}
This depends on an architecture. On many 8-bit microcontrollers comparing to zero requires a single instruction, while comparing to a specific number other than zero requires two instructions.
The first code would translate to this:
LDAA x
CMPA #1
BNE loc
...
This loads x
into a register, compares the register to 1
, and jumps on equality.
The second code would translate to this:
LDAA x
BNE loc
Loading x
into the register sets zero flag, so jumping on equality to zero can be done right away. This saves two bytes of code memory, and two CPU cycles.
You can check if that is what's happening on your platform by compiling a small sample to assembly, or by disassembling your actual code.
You may want to measure it, but most likely those two are exactly the same speedwise (on machine code level they are pretty similar).