For Javascript game engines, is re-using a global variable more or less efficient than making locals?

StackOverflow https://stackoverflow.com/questions/15829147

Pregunta

A lot of Javascript performance guides tend to emphasize two points:

  • Stay within scope; looking up variables progressively through each scope is expensive.
  • Don't abuse the garbage collector by creating unnecessary variables constantly.

For programs that run at 60fps or similar high speeds, is there a difference in performance? JSPerf seems to go between the two on my system, so I'd like to know a little more about how to optimize for this type of stuff. Considering the following two code samples:

var t0;

function doSomethingGlobal() {
    t0 = getWhatever();
    t0.func1();
    t0.func2();
}

verses

function doSomethingLocal() {
    var t0 = getWhatever();
    t0.func1();
    t0.func2();
}

http://jsperf.com/global-verses-local

¿Fue útil?

Solución

I think it depends on how often you access globals, and how deeply nested the globals are in the execution context(s). It would be quicker to access a variable from one execution context 'higher', than one from ten levels higher, for instance (depending on the JS engine, I imagine results and engine optimisations would vary).

I've modified your test a bit to have 50 accesses of the global variable, and the results are significant, ~5 times faster for local access in this particular test (for my brief tests in Firefox 19.0 and Chrome 26).

As with all performance related issues, rules of thumb can only get you so far. You have to benchmark your code and make optimisations that make sense for your code.

Otros consejos

Note that your second statement is not entirely correct. You say:

Don't abuse the garbage collector by creating unnecessary variables constantly.

You want:

Don't abuse the garbage collector by allocating unnecessary objects constantly.

It's not locations for storing variables that are the issue (which is what you're talking about when distinguishing between local and global) as local variables will be allocated on the stack, which is cheap and easy. It's keeping track of the objects stored in these locations, which will cost substantially the same wherever you store the references.

As we know, global variables are often slower to look up, so that's one reason to avoid them. They're also harder to work with, and lead to code that's more difficult to maintain, which is to my mind the biggest reason to avoid them. From the garbage collector's point of view, there's no reason to chose one over the other.

Finally, unless you've got a specific reason to believe that variable accesses are slowing down your page significantly, why are you worrying about their performance at all? Write maintainable code first!

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top