Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why modifying global variable increases memory usage in Chrome

Recently I have been playing a little bit with optimization of javascript code to make HTML5 games, targeting especially mobile browsers. I started with comparing engines and gradually simplified compared codes and I have got to something what I don't understand.

The case is I noticed that in Chrome (so I guess all webkit based browsers) modifying global variable causes increasing the used memory. Let me show you two examples:

1) Modifying global variable:

Code:

var globalVariable = 0;

var fps = 60;
window.onload = init;

function init () {
   setInterval (loop, 1000/fps);   
};


function loop (){

    for (var i = 0; i < 1000000; i++) {
     globalVariable =  Math.random();
    }
};

Screen of Memory Timeline: Memory 1

As you can see it has a lot of memory to collect during the first 10 seconds!

2) Creating local variable instead of modifying global one:

The code remains the same, the only change is adding keyword "var" within the loop. globalVariable = Math.random(); becomes var localVariable = Math.random();

Screen of Memory Timeline: Memory 2

As you can see memory usage is really low, for the first 10 seconds it just increases about 0.1MB.

The difference is really huge! I am not able to check it now, but I was informed that in Firefox in both examples the memory usage for both cases looks almost the same.

Can anyone explain me, or point me to the resources where it is explained? Or can anyone suggest me how to modify global variable to not increase the used memory?

like image 708
Jorasso Avatar asked Dec 28 '12 18:12

Jorasso


1 Answers

(first, a quick rant about 'global' variables. there are no global variables in Javascript, there are scopes, including a window-level scope)

But, the answer is that accessing a variable from another scope in a function in Javascript hoists it into the current scope. Here's a fun explanation of the effect.

like image 189
tmcw Avatar answered Oct 23 '22 20:10

tmcw