The right way of using a variable - inside or outside a function loop
javascript, jquery, performance
Solution
The variable is not created during the loop. It is needed in the event handler only, which will be executed on its own. Moving the variable (when it's only needed inside) outside has three problems:
- access to a higher-scoped variable is a littlebit slower
- garbage collection does not collect the value (not memory-efficient)
- possible trouble when async behavior in the event handler accesses the variable but the handler is invoked multiple times
The second point is also the answer to your question:
Is it better practice to create on each loop a new variable which be released when the function exits or "catch" the memory for the entire run and avoid recreating a variable each time?
It hardly makes sense to waste the memory for the entire time, creating the function scope is fast. Moving the declaration away from the use of the variable can be considered bad practise, moving it to a different scope even can introduce errors.
Preallocating the memory would make sense if you run on a machine with big memory, and creating/deleting the object (that stays constant for all handlers) is slow.
Problem
I was making a loop when suddenly got hit by a question. Which is supposed to be "the right way": ``` // code.. $('tr','#my_table').each(function(){ $(this).click(function(){ var show_id = $(this).attr('data-show-id'); // code.. // code.. }); }); // code.. ``` OR ``` // code.. var show_id = 0; /* HERE */ $('tr','#my_table').each(function(){ $(this).click(function(){ show_id = $(this).attr('data-show-id'); // code.. // code.. }); }); ``` In the first example I create for each `tr` a new variable `show_id`. In the second I use the same global `show_id` for all of the `tr`'s in the table and I repopulate it on each tr. So the question wold be: REGARDLESS of the programing language - Is it better practice to create on each loop a new variable which be released when the function exits or "catch" the memory for the entire run and avoid recreating a variable each time?