最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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.

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.

Share Improve this question asked May 4, 2011 at 14:08 BHSPitMonkeyBHSPitMonkey 6555 silver badges15 bronze badges 2
  • As it might seem, the inside the loop variable, with a limited scope, will be recreated everytime it loops, as its space in memory and its pointer. I may be talking horse feathers, but in my opnion, the declaration outside the loop will be more effecient than the inside. – marcelo-ferraz Commented May 4, 2011 at 14:15
  • 1 @NoProblem: JavaScript does not have block scope. Please don't misinform. This is not a matter of opinion. – Matt Ball Commented May 4, 2011 at 14:17
Add a ment  | 

5 Answers 5

Reset to default 8

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

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

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

This depends on the implementation of the interpreter. Strictly speaking, yes, it may have a slightly higher overhead; but depending on the GC mechanism this should be cleared reasonably quickly too.

Douglas Crockford remends putting all the var assignments at the top of a function, i.e. outwith any loops.

发布评论

评论列表(0)

  1. 暂无评论