What would be more efficient in terms of computer resources. Putting the event handler inside of a loop like this:
$('ul li').each(function()
{
$(this).mouseover(function()
{
// code to do something
});
Or having the function outside of the loop and creating a call to it inside the loop like this:
$('ul li').each(function()
{
$(this).mouseover(function()
{
doStuff($(this));
});
function doStuff(liElem)
{
// code to do something
}
It seems like to me that the second option would be easier on the computer because the code to do something wouldn’t be repeated each time the loop iterates. Does the code of the event handler get created in the computer’s memory every time through the loop, or is it just created once? Any thoughts?
There can be various optimizations possible but keeping it specific to the approach you have asked for,
please find the answer as inline comments in the code below
First approach:
Or having the function outside of the loop and creating a call to it inside the loop like this:
Second approach: