DEV Community

Discussion on: Early Returns in JavaScript

Collapse
 
nvdweem profile image
Niels van de Weem

When I run your benchmark it shows that the single exit point is twice as slow as the other two options. It isn't accurate though, the single exit point is assigning a global variable (window.value) which the other examples don't. In effect it has a side effect that the others don't have and I'm guessing it means that it's optimized less because of it.
Might be browser dependant though since you describe not having that difference (I'm running Chrome).

Changing "value=''" to "var value" or "var value=''" (or even "let value=''") to remove the global assignment makes all 3 testcases perform roughly the same.

I'm still a fan of early returns though even though there are cases where it's less readable indeed.

Collapse
 
martinspire profile image
Martin Spierings

Agreed. I've updated it and its about the same:
jsbench.github.io/#d95ae3db82974a3...

I also get different results on different devices. My own CPU does 2 billion on each and 1+3 are green. On my workstation 2+3 (with 0.8 billion) and on my phone its just the first (and 1.2 billion)