Does speed and memory benefit from declaring a variable outside of a JavaScript loop?

There are similar questions for C #, but we haven't seen JavaScript.

Is it common practice to declare variables inside a loop?

Suppose there is a loop of 200 iterations.

Is there a performance requirement (memory and speed) to use sample 2 over sample 1? We are using jQuery for the loop. This improves the readability of the code for us to keep the var inside the loop, but we will switch if this is not best practice or will result in significantly less performance or higher memory usage.

**Sample 1:**
$(this).each( function() {
   var i = $(some_div).clone();
   *** edit i ***
   $(another_div).append( i );
});



**Sample 2:**
var i = null;
*** edit i ***
$(this).each( function() {
   i = $(some_div).clone();
   $(another_div).append( i );
});

      

+3


source to share


4 answers


Example 1 (variable inside) is faster: http://jsperf.com/variable-outside-faster



But the difference is not worth taking care of.

+3


source


This is micro-optimization, stop doing it.

Instead, invest energy in readable, readable code and do documentation and code testing.



However, there are some high-level issues worth optimizing for:

  • Removing bloated abstractions like jQuery that make you an order of magnitude slower.
  • Reducing the amount of rendering and drawing you do on screen
  • Reducing the great complexity of your algorithm
  • Reducing the response time of the client server.
+3


source


It will depend on the implementation, but in principle I don't think there will be a noticeable difference in performance. Since you are using jQuery for the loop, the variable i

will be in the function scope in the first case and in the outer scope in the second case. This may have a slight effect on memory allocation, but I doubt it will be noticeable. The only way to make sure he picks an implementation and tries to measure the performance in it.

0


source


They are potentially semantically different, so this is an apples to oranges comparison: for example, if you used i

ajax inside callbacks instead of synchronously, you would almost certainly use the latter assignment i

multiple times, rather than each of the different values, if you made this change.

the pure guess follows:

Hence, we know that if you were to use the full potential var

inside the form, you would need different memory addresses for each i

, then it should do more work.

It $.each

will take considerable analysis to determine what is using its callback argument. Hence, if this is a valid optimization, I suspect that most JS compilers won't be able to do this, and manually this should give you (constant time) speed and memory improvement.

Other considerations:

More lexical scopes potentially mean a linear increase in the cost of searching for a variable.

0


source







All Articles