rokyed
rokyed

Reputation: 520

Which one is better and why ? for loop javascript

A.

    var a = array();
    for(var i = 0; i< 100;i++) {
        var obj = new Obj(parameters);
        a.push(obj);
    }

B.

    var a = array();
    var obj;
    for(var i = 0; i< 100;i++) {
        obj = new Obj(parameters);
        a.push(obj);
    }

Which one is faster at getting processed and memory wise, is there any difference?

Upvotes: 0

Views: 60

Answers (1)

jfriend00
jfriend00

Reputation: 708036

There is no difference execution-wise. The var obj is hoisted to the top of the function scope in both cases at the time the code is parsed so it results in the same actual code when the interpreter runs it. For more on hoisting, see this article.

There should be no difference in execution speed (once parsed) because both compile to the same actual code. If you wanted to see if there was a meaningful difference in parse speed (which seems unlikely), you'd have to build a test case and then test the performance in several different browsers.

If you want to optimize the performance, then you can eliminate the intermediate variable entirely in the code you showed us:

 var a = [];
 for (var i = 0; i< 100;i++) {
     a.push(new Obj(parameters));
 }

There are different opinions on which is a better way to write the code from a readability point of view. Many suggest that all variables should be declared at the top of the scope in which they are defined. Others like to define them closest to first use. Since both result in the same actual execution, this is more a matter of preferred style than anything else.


With the introduction of the let keyword in ES6, there will be block scope in Javascript so there will be a third option using let obj = new Obj(...) which can result in different execution than the var definition.

Upvotes: 2

Related Questions