Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does using var in a tight JavaScript loop increase memory-related overhead?

For example, would this:

while (true) {
    var random = Math.random();
}

... be less efficient than the following, in most implementations?

var random;
while (true) {
    random = Math.random();
}

Thanks for your input.

Edit: In case it wasn't obvious, I'm mostly worried about lots of repeated (de)allocations occurring in this example.

like image 938
BHSPitMonkey Avatar asked May 04 '11 14:05

BHSPitMonkey


3 Answers

JavaScript does not have block scoping.

In the first example, the var text declaration is hoisted out of the while block. In both cases, the variable is declared only once. In both cases, the variable is assigned a value once per iteration of the while loop.

var

  • function-scoped
  • hoist to the top of its function
  • redeclarations of the same name in the same scope are no-ops
like image 198
Matt Ball Avatar answered Oct 04 '22 01:10

Matt Ball


No, variables are initiated upon entry into the scope, so random exists before the var statement is even reached.

like image 40
Matt Molnar Avatar answered Oct 04 '22 00:10

Matt Molnar


JavaScript doesn't have block scope, and random's declaration would be hoisted to the top of its scope anyway (variable object).

like image 27
alex Avatar answered Oct 03 '22 23:10

alex