jquery - Speed and memory benefit from declaring variable outside JavaScript loop? - Stack Overflow

admin2025-04-09  0

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 );
});

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 );
});
Share Improve this question edited Apr 5, 2012 at 0:34 Crashalot asked Apr 4, 2012 at 23:51 CrashalotCrashalot 34.6k63 gold badges284 silver badges460 bronze badges 7
  • @Crashalot: In sample 1, variable is created at each iteration. In sample 2, variable is reused. Have you done some performance tests? – Marat Tanalin Commented Apr 4, 2012 at 23:53
  • No, we were curious to hear best practices since this must be an established pattern. We assume there is a performance gain because the var is reused, but wondered if there were significant advantages. It's simpler to read the code if the vars are inside the loop, but if speed and memory performance requires declaring outside, then we will. – Crashalot Commented Apr 4, 2012 at 23:56
  • Each implementation could be different. For all you know without further research any given interpreter could optimize it on the fly and remove any penalty. – rlperez Commented Apr 4, 2012 at 23:56
  • One lexical scope lookup vs non closed over variables. I would imagine that the difference would be negligible and vary wildly between browsers. Probably not worth the theoretical performance gain. Write what makes sense. – J. Holmes Commented Apr 5, 2012 at 0:07
  • Your two samples are not equivalent. – gilly3 Commented Apr 5, 2012 at 0:10
 |  Show 2 more ments

4 Answers 4

Reset to default 4

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

But the difference is not worth enough to care about.

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:

  • Removing bloated abstractions like jQuery that make you an order of magnitude slower.
  • Reducing the amount of rendering and drawing you're doing on screen
  • Reducing the big O plexity of your algorithms
  • Reducing the latency of server-client trips.

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 parison: 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 pilers 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.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744202612a235871.html

最新回复(0)