Reputation: 649
I am trying to make my javascript games as light and smooth as possible, and here is my dilemma : What is worse, too many garbage or too many global variables ?
On one hand, to avoid micro pauses caused by garbage collection, I should avoid using temporary variables in my functions and for loops, those which I create with "var" and which die at the end of the function, because they become garbage.
But on the other hand, if I replace all these temporary variables with as many persistent global variables, won't it make my program heavier to run for the browser's javascript engine ?
What is worse ?
(Judging only on ease of writing and avoiding bugs, I would never get rid of temporary variables. For example, if a function A calls a function B and both have a for(i=...) instead of for(var i=...), function B's for loop will accidently mess up with function A's "i" since it would be the same global variable instead of two different temporary ones belonging to each function, and there will be bugs. The only way to avoid this with global variables is to use longer more explicit names, and that is annoying when you have to write them a lot. But garbage collection micro pauses are annoying in games so I must avoid temporary variables. What a dilemma.)
Upvotes: 0
Views: 797
Reputation: 2312
Javascript has automatic garbage collection. While you don't want to get carried away with throwaway variables, using functions to properly scope your variables and manage your application will make this a non-issue in almost every case.
You should be using for(var i...)
for all your iterative loops because, as you said, the other options are either 1) stupid long variable names or 2) namespace collisions.
In general you should use functions to namespace and modularize the components of your game/application. To avoid any real name space collisions you can wrap your entire application in a function to create a private namespace, like:
(function(){
//code goes here
})();
I recommend you read Memory Management and this StackOverflow question on global variables.
Writing Fast, Memory-Efficient JavaScript By Addy Osmani is also a great article on Garbage Collection in Javascript.
Upvotes: 2