Question

I have this code which manipulates the asp.net treeview html code.

This code gets run frequently, so its important that it runs as fast as possible.

I want to learn more about jquery selectors and improving its speed. So far I was able to get this code myself.

Some things I am not sure about is if you want the third child element, do I use [2] or .eq(2) or :nth-child(2)? Also what if I use $ to select something that was from an array of selected stuff, is this necessary, or is it already selected?

Does anyone know any tricks or hints I can do to improve my jquery select efficiency?

Thanks.

function showResultsOnTreeview(treeviewID, filenameDictionary) {
    var sectionNodes = $("#" + treeviewID + " > table");
    var numOfSections = sectionNodes.length;
    var i, j, sectionName, divContainer, itemNodes, numOfItems, itemName, itemTag, itemPath;

    for (i = 0; i < numOfSections; i += 1) {
        sectionName = $(sectionNodes[i]).text();
        divContainer = $(sectionNodes[i]).next('div');
        divContainer.hide();
        itemNodes = $('table', divContainer);
        numOfItems = itemNodes.length;
        for (j = 0; j < numOfItems; j += 1) {
            itemTag = $('td', $(itemNodes[j])).eq(2);
            itemTag.removeClass('treeViewResult');
            itemName = getNameFromItem($(itemNodes[j]).text());
            itemPath = filenameDictionary[itemName];
            if (itemPath != null) {
                if (itemPath.indexOf(sectionName + "/" + itemName) != -1) {
                    itemTag.addClass('treeViewResult');
                    divContainer.show();
                }
            }
        }
    }
}
Was it helpful?

Solution

There is some optimisation you can do. The first on is for sure to use .eq() instead of []. Like here, you hare creating a jQuery object :

var sectionNodes = $("#" + treeviewID + " > table");

But then later, you do this :

sectionName = $(sectionNodes[i]).text();
divContainer = $(sectionNodes[i]).next('div');

Here you are creating 2 more, unneeded, jquery object, you could just do this :

sectionName = sectionNodes.eq(i).text();
divContainer = sectionName.next('div');

Then, i do't know if you have a different way to do it, but if you can remove the "loop in a loop", that would be great.

After, instead of using context selectore ($('selector', $element)), use find. Context use find so it will reduce the number of function calls. Take this line for example :

 $('td', $(itemNodes[j])).eq(2)

You are creating 2 jQuery object when you can do the same without an extra object and could use .find():

itemTag = itemNodes.eq(j).find('td').eq(2);

Basicly, use .find() instead of context and avoid creating unneeded jQuery object. Hope that will help.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top