Hacker News new | ask | show | jobs
by Gaelan 1865 days ago
> eg. declare variable up front, not within loops

I have trouble believing modern JS engines wouldn’t optimize this to the same thing.

1 comments

Behaviorally they aren't the same thing, so that's not a straightforward mechanical translation. For example if the variable is an object instance then if escape analysis can prove the variable doesn't outlive the loop, then it can be put on the stack & then yes there wouldn't be any benefit to the suggested change. Although deoptimization makes stack allocation more complicated, so JS engines are more conservative here than say JVM runtimes.

But it's really easy for escape analysis to fail, it has to be conservative. So you can end up heap allocating a temporary object every loop iteration quite easily.