0

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?

asked Feb 18, 2015 at 2:12

1 Answer 1

2

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.

answered Feb 18, 2015 at 2:14
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.