I have a quite complicated question to ask 🙂
I am currently working on a html5 canvas game. The variables which are specific to a map of the game are in a separate file (let’s call it game.js), separated from the game engine (let’s call it engine.js).
I have read that global variables are slower to use in JS than local variables. Therefore, in game.js, I create a global variable which contains all the game-specific variables. In engine.js, I copy this global object to local variables, there I delete this global object.
This is working. But I know that assigning objects only pass a reference to these objects.
Therefore my question is: will the performance of that be as if I had declared all the variables directly as local variables in engine.js, as I delete the global object at the end of the initialisation, or will it be slower, as if my local variables in engine.js were just references to a global object?
I could declare all the variables as local in engine.js, but it would be useful for me to separate what is specific to the map, if later I want to make other maps/games.
For example:
game.js:
Game = function() {
this.x = 16;
this.y = 16;
this.myObject = {"test": "hello", "action": "none"};
}
game = new Game();
engine.js:
//…
var x = game.x;
var y = game.y;
var obj = {"test": game.myObject.test, "action": game.myObject.action};
//…
In this example, will the performance of x, y and obj be as fast as local variables, or slower?
Note: I didn’t really check the difference between performances of global vars, and local vars, but I assume what I read about it is right.
Hope my question was clear enough and not silly 🙂 If you have any ideas… Thanks!
In modern browsers, there probably isn’t much performance difference between local and global variables.
However there is an issue with memory consumption – global variables persist as long as the page stays open whereas local variables are garbage collected after control leaves their scope. Using local variables reduces the chance of having a memory leak.
Update
The long-winded discussion in the comment thread prompted me to write a test script to measure execution speed differences contrasting global and local scope access.
Initially there seemed to be no difference and results vary with no specific preference towards one or the other. However @DaveNewton provided a counterexample which consistently shows better performance for local variables by an order of magnitude.
Firefox 7
Internet Explorer 9
Google Chrome 14
Test script itself
A counter-example, demonstrating faster access to local variables.