Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More efficient jQuery sort method for DOM elements based on numerical attribute

I have some simple jQuery written to sort some elements based on a numerical attribute as illustrated at http://jsfiddle.net/MikeGrace/Vgavb/

// get array of elements
var myArray = $("#original div");

// sort based on timestamp attribute
myArray.sort(function (a, b) {

    // convert to integers from strings
    a = parseInt($(a).attr("timestamp"), 10);
    b = parseInt($(b).attr("timestamp"), 10);

    // compare
    if(a > b) {
        return 1;
    } else if(a < b) {
        return -1;
    } else {
        return 0;
    }
});

// put sorted results back on page
$("#results").append(myArray);

It works fine but I don't think it will scale because a total of 185 jQuery calls are made, 184 of them which are getting the attribute of an element to do the comparison.

What is a more efficient way to do this sorting with jQuery?

like image 506
Mike Grace Avatar asked Dec 21 '10 19:12

Mike Grace


2 Answers

If you're worried about performance, and know for sure where the attribute comes from, you can use the DOM methods directly, .getAttribute() in this case:

a = parseInt(a.getAttribute("timestamp"), 10);
b = parseInt(b.getAttribute("timestamp"), 10);

You can test the difference here, as you see it's more than a little speed boost, .attr() does a lot of extra work internally, ultimately calling .getAttribute() itself in this case anyway.

like image 93
Nick Craver Avatar answered Oct 08 '22 04:10

Nick Craver


If you need to do lots of sorting repeatedly, it would be good to work towards a more native approach that doesn't involve jQuery. Otherwise, there really isn't much that is going to make a noticeable difference.

Here are some tests trying a few different approaches -> http://jsperf.com/jquery-sort-by-numerical-property/2

like image 36
Mike Grace Avatar answered Oct 08 '22 06:10

Mike Grace