0

Imagine I have a function that is being called very often and needs to use a variable internally.

function busyFunction() {
    var intermediateResult;
    /* compute something */
    return something;
}

As I understand, in this first example the browser will allocate memory for the variable and then schedule it for garbage collection at some point.

var intermediateResult;
function busyFunction() {
    /* compute something */
    return something;
}

I know the second example will pollute the scope outside of busyFunction. But since the the memory for the variable would not be garbage collected until the parent function is, would this be beneficial for performance? If I'm wrong here or if the effect is negligible, I'd rather use the first cleaner example.

TeeBoek
  • 33
  • 4
  • Just let the GC do its job instead of polluting the global scope. And you won't get unexpected results if this function is called by differents async ones – Cid Nov 27 '20 at 09:14
  • @Cid good point with the async calls. – Dropout Nov 27 '20 at 10:17

2 Answers2

1

Declaring variables in a higher scope makes them a bit slower to access (very so in the global scope), and - more importantly - harder to optimise for the compiler. The garbage collection cost is negligible. I will expect this to actually be slower. The difference should be quite small (hardly measurable), but as always, benchmark it yourself on your actual code with real data.

The only case where the performance would improve is if you want to persist a value between the invocations, and would gain your advantage by not repeatedly running costly initialisation code. Especially if you can make the variable a constant initialised before the function is called.

In general, aim for readable and idiomatic code, optimising compilers do as well.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
-1

In short, yes. You consume less resources, because every time the function gets executed you don't create a variable in it's scope that then gets thrown away after the function execution ends. Personally I'd advise to create an object which holds both the variable and the function so that the variable doesn't just "float around", but that's detail.

Another thing however is code readability. I presume the example in the question is a simplified version of what you're dealing with. Here it basically comes down to balance between readability and efficiency. If you think it would be confusing to leave it outside then leave it in the function unless the advantages of having it outside heavily outweigh the fact that the code is less confusing.

Unless the performance improvement is very significant I'd advise to leave it in the function for clarity.

Dropout
  • 13,653
  • 10
  • 56
  • 109
  • V8 developer here. This answer is incorrect: pulling the variable out of the function will use _more_ resources, not less. Having local variables in functions is essentially free. – jmrk Feb 07 '22 at 12:58