简体   繁体   中英

Efficiency of nested functions inside of jQuery loops

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:

$('ul li').each(function()
{
    // Maybe you might like to declare some variables here
    $(this).mouseover(function()
    {
        // code to do something

        // Maybe you might like to use the variables declared in above function

        // Disadvantage over other approach
        // The code written here will need to store the context information of the outer function and global context

        // Advantage over other approach
        // You can directly access the variables declared in the above function
    });
}

Or having the function outside of the loop and creating a call to it inside the loop like this:

Second approach:

$('ul li').each(function()
{
    // Maybe you might like to declare some variables here
    $(this).mouseover(function()
    {
        doStuff($(this)); 
    });
});

function doStuff(liElem)
{
    // code to do something

    // Advantage over other approach
    // The code written here will need to store the context information only for the global context

    // Disadvantage over other approach
    // You cannot directly access the variables declared in the outer function as you can in the other approach,
    // you will need to pass them to the doStuff function to access here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM