# Which processes faster?

All of my programming knowledge has been self taught so there are some holes in it (like swiss cheese!)
That being said...

Which is faster to process:

IF / ELSE

or

math

What I mean is which of these two codes would process faster:

int y=0;
if (x>10) {y += 3;}
if (x>100) {y += 5;}
if (x>1000) {y += 8;}

Or something like this:

int y=0;
y= ((x>10)*3) + ((x>100)*5) + ((x>1000)*8 )

I started programming WAY in the past (TRS80 Model I) but I failed to
learn C++ until just the past few years or so.

the formula is somewhat of a hack and performs the same number of tests but more additions but likely a bit faster

you could go faster using else statements (i.e. if you know you are not > 100, then why bother testing for > 1000) and do all the additions at once

``````int y=0;
if (x>1000)   {y += 16;}
else
if (x>100)    {y += 8;}
else
if (x>10)     {y += 3;}
``````

you could try both in codes and time how long it takes to execute in microseconds for each option (but you'll find it's so fast that you can't measure it and fall into the 4 microseconds measure)

"Problem" is
y= ((x>10)*3) + ((x>100)*5) + ((x>1000)*8 )
isn't pure math. x>10 already is a logic test

here is a stupid code to test time it takes to do 100,000 times the same thing but using different maths

plug a wire in A0 and touch it with your finger from time to time to vary the x value kinda randomly

``````void setup() {
int y = 0;
int x;

unsigned long t;
Serial.begin(115200);
Serial.println("\n------------- TEST -------------");
// ------------------------

y = 0;
t = micros();
for (unsigned long i = 0; i < 100000ul; i++) {
if (x > 10) y += 3;
if (x > 100) y += 5;
if (x > 1000) y += 8;
}
t = micros() - t;
Serial.print("simple if =\t\t"); Serial.print(t); Serial.println(" microsecs");
// ------------------------

y = 0;
t = micros();
for (unsigned long i = 0; i < 100000ul; i++) {
if (x > 1000) y += 16;
else if (x > 100) y += 8;
else if (x > 10)  y += 3;
}
t = micros() - t;
Serial.print("if else  =\t\t"); Serial.print(t); Serial.println(" microsecs");

// ------------------------
y = 0;
t = micros();
for (unsigned long i = 0; i < 100000ul; i++) {
y = ((x > 10) * 3) + ((x > 100) * 5) + ((x > 1000) * 8 );
}
t = micros() - t;
Serial.print("formula =\t\t"); Serial.print(t); Serial.println(" microsecs");
}

void loop() {}
``````

the console output is

``````------------- TEST -------------
simple if =     11200136 microsecs
if else  =      11200004 microsecs
formula =	    11200028 microsecs
``````

as you can see the if else is the more optimized but 132 microseconds difference over 100,000 tests is totally insignificant…