2
for(var i=0;i<lines.length;i++) { var line = lines[i]; 

vs

var line; for(var i=0;i<lines.length;i++) { line = lines[i]; 

Do this two snippets have different performance. If yes, please explain why.

2 Answers 2

1

I have run a benchmark on this and have found that there is pretty much no difference in performance.

If you would like to recreate it:

var lines = new Array(#BIG_NUMBER#); lines.fill(#BIG_OBJECT#); var a = (new Date()).getTime(); for(var i=0;i<lines.length;i++) { var line = lines[i]; } var b = (new Date()).getTime(); var line; for(var i=0;i<lines.length;i++) { line = lines[i]; } var c = (new Date()).getTime(); console.log("a:" + (b-a) + " b:" + (c-b)); 

This makes sense, as there is almost no difference, both cases will create a local object that will be stored, and will be reassigning it multiple times.

Sign up to request clarification or add additional context in comments.

Comments

0

Your code will work differently in both the cases.

In the first one line is a global variable an will be accessible outside the for loop, which is not the case in second one.

So I don't think performance comparison makes any sense here!

Even then, declaring a variable again and again is unnecessary though I don't think it is a complex operation. But yes declaring it repetitively will deteriorate the performance.

4 Comments

In the second one the variable also be global and accesible outside of for loop. In javascript there are no block scope only function scope.
@jcubic there is block level scope in ES6.
OP ask about var not let.
Even if you were right, you've got your examples mixed up.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.