简体   繁体   中英

Am I improving performance I declare a variable outside of busy function in JavaScript?

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.

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.

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 const ant initialised before the function is called.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM