Question

Simple question - is it worth to create local equivalents of global variables inside of functions if we make a lot of actions on them?

var global = $(elements);

function foo(){
    var local = global;
    // lots of actions on local
}

function foo2(){
    // lots of actions on global
}

As far as I know, refering to global variables forces script to access the global scope and get values from them. I just wonder if is it worth to make an equivalents of global inside of functions which uses them?

Was it helpful?

Solution

It helps to create a local copy because variable resolution starts at the most local and goes toward looking in the global namespace, making it slower.

Much slower in certain older browsers.

Here is a benchmark: http://jsperf.com/global/25

Update:

Added an updated version with another test case that in theory shows that most of the performance impact comes from going up the scope chain.

http://jsperf.com/global/30

OTHER TIPS

You don't have nothing to worry about. Usually using global variables is discouraged because can make you code harder to mantain. The performance impact of a global variable is very little.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top