Tamás Polgár
Tamás Polgár

Reputation: 2262

Which is more efficient in a function: conditional execution or conditional exit?

I would really hear some opinions on which of the following solutions is more efficient in JavaScript/TypeScript:

function whatever(param) {
   if (param === x) {
      doStuff();
   }
}

or

function whatever(param) {
   if (param !== x) { return false; }
   doStuff();
}

Obviously the second one reduces the number of blocks and improves code readability, but does it offer any benefits or drawbacks compared to the first one?

Upvotes: 2

Views: 119

Answers (4)

Jonas Wilms
Jonas Wilms

Reputation: 138257

In assembly you'd write both as:

 // first
 whatever:
   CP x, param
   JP nz, whatever2
   CALL doStuff
whatever2:
   RET

// second:
whatever:
  CP x, param
  JP z, whatever2
  RET
whatever2:
  CALL doStuff
  RET

So while the first one uses 4 instructions, the second uses 5. So in case the JS engine is able to optimize it down to this optimal bytecode (very unlikely, but it makes estimations easier), the second one will be 1 tick slower, which is less than a nanosecond.

Upvotes: 4

Utkarsh Bhimte
Utkarsh Bhimte

Reputation: 335

It depends on the use case here, I don't think there is much difference in the context of performance or code readability.

I would personally go with the second approach as it also reduces indentations. Indentation gives me a clear indication of initialization of newer block. If I notice a new indent, I would assume there should be a for loop here or an if statement.

If the code is part of the main flow or the most common flow, I wouldn't want that to be further indented.

Again, All this is my personal style guide rules which have helped me to be able to deduce the code logic faster.

Upvotes: 1

Frank Puffer
Frank Puffer

Reputation: 8215

There is no significant difference in efficiency, even if you have more than one of these preconditions in your function. No matter what language you use. Some compilers will probably even generate the same machine instructions from both versions.

Stop thinking about efficiency too much. Think about readability and maintainability!

Upvotes: 1

SpeedOfRound
SpeedOfRound

Reputation: 1278

Here is a test where I run the comparison 10000 times.

The difference is pretty much non-existant.

Upvotes: 3

Related Questions