Given the following code snippet:
if (condition1 && condition2) {
// ACTION 1
} else if (!condition1) {
// ACTION 2
} else {
// ACTION 3
}
Does it make a difference in performance if I restructure it this way:
if (condition1) {
if (condtion2) {
// ACTION 1
} else {
// ACTION 3
}
} else {
// ACTION 2
}
No, not unless condition1 contains a heavy method call of some sort that would be repeated otherwise. And if it is it would be better to call it first and just compare the results just to keep it easier to read.
let condition1Result = condition1();
if (condition1Result && condition2) {
// ACTION 1
} else if (!condition1Result) {
// ACTION 2
} else {
// ACTION 3
}
Just comparing two values has a negligible performance hit in almost all scenarios so focusing on readability of the code of micro-optimization is always a good idea.
In the first case, if condition1 is false, then there will be a short-circuit operation which basically means that you would not need to check condition2 and completely skip that block altogether.
Whereas in the second case, you can skip two blocks if condition1 is false.
As far as the performance is considered, it won't have a significant difference since they are just comparisons. So you should use whichever form is more readable and intuitive in your particular context.
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