int i = 3;
Is there any performance difference between this code:
if(i == 2)
DoA();
if(i == 3)
DoB();
if(i == 4)
DoC();
And this code:
if(i == 2)
DoA();
else if(i == 3)
DoB();
else if(i == 4)
DoC();
I’m wondering if using optional ELSE affects how the CPU understands the code or not. I always think when we use the second approach, if i is 2 then the CPU does not check the other two conditions, but in the first approach although the first condition is true (i == 2) but the CPU does check the second and third conditions. Is this true?
Of course it does affect — for better! It’s totally the opposite of unecessary, since by using those elses the compiler will skip the other if-checks and get better performance.
But you shouldn’t be worring about it, the difference in performance in your example is so minimal it’s insignificant.