28

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...
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jeffreyveon
  • 13,400
  • 18
  • 79
  • 129

13 Answers13

22

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.

Josh Stodola
  • 81,538
  • 47
  • 180
  • 227
  • 12
    I disagree. Maybe a little easier to read, but harder to maintain, even harder when it is not you but any other developer who has to understand the code. That is my opinion, in general terms, about functions having too much "return" points. – Guido Nov 30 '09 at 16:35
  • 12
    I respectfully disagree with your disagreement. In my experience, using this type of construct has never affected maintainability. If anything, it has made it better; the fewer amount of nested statements tends to increase maintainability for me. I do, however, agree with your remark about having too many "return points". Generally, I only have return points at the beginning and end of the functions. At the beginning for the obvious exclusions, and at the end to serve the function purpose. – Josh Stodola Nov 30 '09 at 17:28
  • 7
    There is merit to both side. My personal experience is that too many nested if-elses is a nightmare - especially if one of the two conditions is really short and so we can do with a return statement to quickly terminate it. This definitely makes it more readable. – jeffreyveon Dec 01 '09 at 10:00
  • I am on the 'return' side. Sometimes its nice to have one return point, but when the code is really long and heavily nested and you are troubleshooting your way through some certain conditions, its nice to hit a 'return' and stop reading. – Dave Pile Aug 21 '15 at 07:53
  • 1
    IMO (1) if/else is easier to read (due to indentation) (2) more maintainable and (3) leads to more "beautiful" code – Alexander Mills Jun 07 '16 at 18:05
6

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.

Community
  • 1
  • 1
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
4

"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)
just somebody
  • 18,602
  • 6
  • 51
  • 60
4

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    
}
Sudhir N
  • 4,008
  • 1
  • 22
  • 32
3

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.

Chris Clark
  • 4,544
  • 2
  • 22
  • 22
2

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

Karl Adler
  • 15,780
  • 10
  • 70
  • 88
1

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.

Sune Rievers
  • 2,676
  • 3
  • 25
  • 29
1

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Emre Yazici
  • 10,136
  • 6
  • 48
  • 55
  • 2
    Citation needed (for "not a good programming habit")! :-) It's a matter of opinion whether it's better to nest if-elses or return early; there's no definitive winner just like tabs vs spaces, vi vs emacs etc. Personally I believe it *is* better to return early (as in the first form) but I recognise opinions will differ. – Andrzej Doyle Nov 30 '09 at 17:10
  • You are right "there's no definitive winner", but it is far from "vi" vs "emacs"; it is more like "break in for loop" vs "while loop" or "continue in while/for loop" vs "an outer if block". I always prefer the second ones. – Emre Yazici Nov 30 '09 at 17:41
1

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.

0

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

Stefan Kendall
  • 66,414
  • 68
  • 253
  • 406
0

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.

aubreyrhodes
  • 777
  • 4
  • 16
0

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.

Mike Dunlavey
  • 40,059
  • 14
  • 91
  • 135
0

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.

Akansh
  • 1,715
  • 3
  • 15
  • 34