Search code examples
javascriptperformancememorygarbage

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


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


Solution

  • 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.