I always use multiple if statements when coding:
if(logicalCheck){
...
}
if(secondLogicalCheck){
...
}
and rarely use If Else. I understand that using my way means that more than one of my logical checks can be fulfilled and only one in an if else chain can occur.
My question is, is there any performance benefits in using one method over the other in C, Java or JavaScript? Is there anything particular wrong with using multiple if statements?
Using only if
, interpreter or whatever will test all conditions but if you use else if
(if possible) then on passing any condition , next else if
will not be tested or checked.
if (age < 10){
// do something
}
if (age < 20 && age > 10){
// do something
}
if (age < 30 && age > 20){
// do something
}
All conditions will be tested/compared
but in this scenario
if (age < 10){
// do something
}
else if (age < 20 && age > 10){
// do something
}
else if (age < 30 && age > 20){
// do something
}
if age is 5, only first condition will be tested.
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