Why should I declare a variable outside a function and assign a value in a loop use more memory than a local var?

advertisements

I am doing 2 simple tests and profiling them in the google devtools timeline. Declaring a variable outside the function and assigning it a new value in a for loop seems to allocate lots of memory and triggers the garbage collector repeatedly.
On the other hand, declaring the variable in the scope of the function allocates less memory or no memory at all.
Here is the first case:

(function() {
  function createVars() {
    var i;
    var b;
    for (i = 0; i < 10000; i += 1) {
      b = Math.random();
    }
    requestAnimationFrame(createVars);
  };

  requestAnimationFrame(createVars);
}())

And the second one:

(function() {
  var b;

  function createVars() {
    var i;
    for (i = 0; i < 10000; i += 1) {
      b = Math.random();
    }
    requestAnimationFrame(createVars);
  };

  requestAnimationFrame(createVars);
}())


I would have expected the opposite or at least a similar behaviour.


First case, you create a 'b' variable each time you call 'createVars'. Second case, you use only one variable. Always the same. :)