if(var == something) {
A();
B();
} else if(var == something_else) {
A();
B();
C();
} else {
assert(false);
}
How can i avoid duplicate code of calling A() and B() in both if
cases. Should i use switch case like,
switch(var) {
case something:
case something_else:
A();
B();
break;
}
if (var == something_else)
C():
What is the better solution? Is there any performance penalty in switch
vs if else
?
if (var == something || var == something_else) {
A();
B();
}
if (var == something_else) {
C();
}
If you also need the else
, you can do this:
if (var == something || var == something_else) {
A();
B();
if (var == something_else) {
C();
}
} else {
assert(false);
}
In regards to your question,
Is there any performance penalty in switch vs if else?
Please read the answers to this question:
Is 'switch' faster than 'if'?
In short, normally there wouldn't be any noticeable difference. So you should write your code with the readability in mind. Between if/else
and switch
, just choose whatever is more natural.
As calling order doesn't matter, try this:
switch(var) {
case something_else:
C();
case something:
A();
B();
break;
default:
assert(false);
break;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With