Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If Statement Performance

Tags:

javascript

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
}
like image 970
Sammy Avatar asked Apr 22 '26 16:04

Sammy


2 Answers

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.

like image 130
Karl-Johan Sjögren Avatar answered Apr 24 '26 07:04

Karl-Johan Sjögren


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.

like image 35
Rachayita Giri Avatar answered Apr 24 '26 06:04

Rachayita Giri