nick
nick

Reputation: 1998

JS operator performance

From a performance perspective, is it better to use:

if (input1 === x && input2 === y || input1 === z && input2 === y) {
  // do something
}

or:

if ((input1 === x || input1 === z) && input2 === y) {
  // do something
}

Upvotes: 0

Views: 54

Answers (2)

Dave_cz
Dave_cz

Reputation: 1210

There will be no real difference unless that script has to run trillion+ times in a loop. Write it so it looks clear & easy to read/understand.

Upvotes: 1

Barmar
Barmar

Reputation: 780879

Because of short-circuiting, putting the test of input2 first is likely to be better than either of the versions you posted. If this fails, it doesn't need to test input1 at all.

if (input2 === y && (input1 === x || input1 === z))

Swapping the order might not be appropriate if there were any side effects or order-dependencies in the test expressions. But comparing simple variables has no side effects.

Upvotes: 1

Related Questions