Sanjay Sanjay - 9 months ago 35
C Question

Which is the faster operation?

I have two variable a and b.I have to write a if condition on variable a and b:

This is First Approach:

if(a > 0 || b >0){
//do some things

This is second Approach:

if((a+b) > 0){
//do some thing

Update: consider a and b are unsigned.then which will take lesser execution time between logical or(||) and arithmetic (+ )operator

this condition will Iterate around one million times.

Any help on this will be appreciated.


Your second condition is wrong. If a=1, b=-1000, it will evaluate to false, whereas your first condition will be evaluated to true. In general you shouldn't worry about speed at these kind of tests, the compiler optimizes the condition a lot, so a logical OR is super fast. In general, people are making bigger mistakes than optimizing such conditions... So don't try to optimize unless you really know what is going on, the compiler is in general doing a much better job than any of us.

In principle, in the first expression you have 2 CMP and one OR, whereas in the second, you have only one CMP and one ADD, so the second should be faster (even though the complier does some short-circuit in the first case, but this cannot happen 100% of the time), however in your case the expressions are not equivalent (well, they are for positive numbers...).