Question

I am working on a project which requires some pretty intricate JavaScript processing. This includes a lot of nested if-elses in quite a few places. I have generally taken care to optimise JavaScript code as much as possible by reading the other tips on Stack Overflow, but I am wondering if the following two constructs would make any difference in terms of speed alone:

if(some_condition) {
    // process
    return ;
}

// Continue the else condition here

vs

if(some_condition) {
    // Process
}

else {
   // The 'else' condition...
}
Was it helpful?

Solution

I always go with the first method. Easier to read, and less indentation. As far as execution speed, this will depend on the implementation, but I would expect them both to be identical.

OTHER TIPS

In many languages, is a common practice to invert if statements to reduce nesting or use preconditions.

And having less nesting in your code improves code readability and maintainability.

"Profile, don't speculate!"

  1. you're putting the cart before the horse (maintainability by humans trumps machine speed)
  2. you should drive your optimization efforts by measurements, which means

    • you should time the execution yourself; it'll obviously differ in different browsers and versions
    • you should only optimize for speed the hotspots of your application (see point 1)

There won't be any difference in performance I would recommend the second example for maintainability. In general it's good practice to have one and only one possible exit point for a routine. It aids debugging and comprehension.

I will use the first approach when ruling out the invalid situations.

Eg. use first approach when doing some validations, and return if any of the validation fails. There's no point in going further if any of the preconditions fail. The same thing is mentioned by Martin fowler in his Refactoring book. He calls it "Replacing the conditions with Guard clauses". And it can really make the code easy to understand.

Here's a java example.

  public void debitAccount(Account account, BigDecimal amount) {
    if(account.user == getCurrentUser()) {
      if(account.balance > amount) {
           account.balance = account.balance - amount
       } else {
          //return or throw exception
       }
    } else {
        //return or throw exception
    }
  }

VS

 public void debitAccount(Account account, BigDecimal amount) {
    if(account.user != getCurrentUser()) return //or error
    if(account.balance < amount) return //or error
    account.balance = account.balance - amount    
}

Maybe slightly, but I don't think it will be measurable unless the rest of the function involves "heavy" (and otherwise redundant since I assume that a return would give same result) js calls.

As a side note, I think this is unnecessary micro optimization, and you should probably look elsewhere for performance improvements, ie profile the script through Chrome's developer tools or Firebug for Firefox (or similar tools) and look for slow/long running calls/functions.

While it depends on the JavaScript implementation of the running browser, there should not be any notable difference between them (in terms of speed).

The second form is preferable since breaking the flow is not a good programming habit. Also think about that in assembly, the jump instruction (micro operation) is always evaluated regardless of the evaluation.

Test it yourself. If this JavaScript is being run in the browser, it will almost certainly depend on the browser's JavaScript parsing engine.

My understanding is that would not make a difference because you branch with the if condition. So, if some_condition is true, the else portion will not be touched, even without the return.

Suppose the return takes 1ms versus the nested if taking 0.1ms (or vice-versa).

It's hard to imagine either one being nearly that slow.

Now, are you doing it more than 100 times per second?

If so, maybe you should care.

When there is only a single if..else the performance is almost the same and it doesn't matter. Use whatever is best readable in your case. But coming to nested statements using return is the most performant compared to if...else and case switch

Talking from my experiences it depends on the condition you are checking.

  1. if .. return is fine and easy to read if you check some boolean condition (maybe setting) that would make the whole following code unnecessary to be executed at all.

  2. if .. else is much easier to read if you expect some value to be either of two (or more) possible values and you want to execute different code for both cases. Meaning the two possible values represent conditions of equal interpretable value and should therefore be written on the same logical level.

In my opinion, return and else is same for the above case but in general if-else and if()return; are very different. You can use return statement when you want to move from the present scope to parent scope while in case of if-else you can check for further if-else in the same scope.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top