if's vs else-if's -- efficiency

Started by
12 comments, last by jitspoe 21 years, 10 months ago
quote:Original post by jitspoe
yeah, you want to order them according to which is the most common, but I was saying if NONE of them occured very often (maybe needed for error checking or something that will happen once every 100 times you run the program -- hypothetical)...

I guess the only difference the "else" makes is a branch at the end -- a tiny bit of mem taken up -- but doesn't affect the number of instructions if all of the conditions are false. It was just on my mind, heh -- thought I'd throw it out there. I don't even remember what I was doing.


If none of them occur very often then what is the point in optimizing it? Your users are hardly going to notice a nanosecond's difference in speed in your error handling code.



[edited by - Sandman on May 31, 2002 7:34:50 AM]
Advertisement
If you have multiple statements switch statement is faster than else if statements
who is it that keeps on nicking WizHarD name !! :P
but you cannot use switch in your example, because switch only compares const against a var and a string, hmm mora than a const (what does our friend mr Compiler will say) !?! :


switch(text){
case "this string rarely occurs":
...
case strcmp( ???/*text maybe ?*/, "this string rarely occurs"):
...
}

dont know what the compiler will say, but i know it wont work

but switch is only in some cases faster, look at this example, where switch will loose:


switch(num){
case 0:
case 1:
case 2:
...
case 65534:
case 65535:
}


and now the same thing with if (you get some 15/16 if calls before you get to your final destination and by the switch 1 to 65536):


if(num > 32536){
if(num > 48123){
...
}
else{
...
}
}
else{
...
}


please finish the codefragments (macros etc are not allowed)
compared with few if/else statements switch will be faster, because there are 1 or 2 instructions less per if;

T2k
if you really wanna optimize it, use a hash table for your error strings.

This topic is closed to new replies.

Advertisement