I am working on a project which requires some pretty intricate JavaScript processing. This includes a lot of nested if
-else
s in quite a few places.
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.
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.
Test it yourself. If this JavaScript is being run in the browser, it will almost certainly depend on the browser's JavaScript parsing engine.
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
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.
Talking from my experiences it depends on the condition you are checking.
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.
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.