Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Speed and memory benefit from declaring variable outside JavaScript loop?

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 );
});
like image 482
Crashalot Avatar asked Feb 21 '23 22:02

Crashalot


1 Answers

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

But the difference is not worth enough to care about.

like image 74
binarious Avatar answered Apr 09 '23 15:04

binarious