Using 'return' instead of 'else' in JavaScript

后端 未结 13 1522
無奈伤痛
無奈伤痛 2020-12-01 14:09

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.

相关标签:
13条回答
  • 2020-12-01 14:23

    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.

    0 讨论(0)
  • 2020-12-01 14:27

    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.

    0 讨论(0)
  • 2020-12-01 14:32

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

    0 讨论(0)
  • 2020-12-01 14:36

    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

    0 讨论(0)
  • 2020-12-01 14:38

    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.

    0 讨论(0)
  • 2020-12-01 14:39

    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 讨论(0)
提交回复
热议问题