There are similar questions for C#, but we didn't see any for JavaScript.
Is it accepted practice to declare variables inside a loop?
Assume a loop of 200 iterations.
Is there a performance imperative (memory and speed) to using sample 2 over sample 1? We're using jQuery to loop. It improves code readability for us to keep the var inside the loop, but we'll switch if it's not a best practice or will result in materially slower 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 );
});
Sample 1 (variable inside) is faster: http://jsperf.com/variable-outside-faster
But the difference is not worth enough to care about.
i
in sample I --- it could just pass it directly to the $(...).append
cal - tobyodavies 2012-04-05 00:17
for (i = 0; i < 10; i++) var tmp = $(something)
. Here it seems declaring the tmp-variable once, outside the loop, would be faster - powerbuoy 2012-04-05 00:23
for
loop in that case, my question was more on performance. Edit: because when I saw the title of the OP's question I thought that was what he meant - powerbuoy 2012-04-05 00:52
This is a micro optimization, stop doing that.
Instead invest energy into writing readable code and doing documentation and testing for the code.
However, there are some high level issues that are worth optimizing for:
That would depend on implementation, but in principle I don't think there will be any noticeable difference in performance. Since you're using jQuery to loop, the i
variable will be in the function scope in the first case, and in the outer scope in the second case. That might have a slightly different effect on memory allocation, but I doubt it would be noticeable. The only way to be sure it choosing an implementation and trying to measure the performance in it.
These are potentially semantically different so this is an apples to oranges comparison:
e.g. if you were using i
inside ajax callbacks instead of synchronously you would almost certainly be using the last assignment to i
several times, rather than each of the different values if you made this change.
pure speculation follows:
Consequently we know that if you were using the full potential of the var
inside form you would need different memory addresses for each i
, then it must be doing more work.
It would take significant analysis to determine that $.each
uses it's callback argument synchronously. Consequently, if this is a valid optimisation, I suspect most JS compilers will not be able to make it, and making it by hand should give you (constant time) speed and memory improvements.
Other considerations:
More lexical scopes potentially mean linearly increasing cost of looking up a variable.