Reputation: 424
I'm sorting a list of <li> elements. I adapted a function on a page that I can't link right now. You can see the live site here. Click on "Sort and Filter" and click any of the Sort by methods (English name, material, status...). All sorts are essentially the same, so CPU time is the same.
My jQuery function looks like this:
jQuery.fn.sort = function() {
return this.pushStack([].sort.apply(this, arguments), []);
};
function sortAscending1(a, b) { return $(a).find(".english").text() > $(b).find(".english").text() ? 1 : -1; };
function sortDescending1(a, b) { return $(a).find(".english").text() < $(b).find(".english").text() ? 1 : -1; };
And I'm calling it from the following jQuery line (s_alf_eng is a clicable div on the page).
$(document).ready(function() {
$(".s_alf_eng").toggle(
function() {
$('.media-status-specie li').sort(sortAscending1).appendTo('.media-status-
},
function() {
$('.media-status-specie li').sort(sortDescending1).appendTo('.media-status-specie');
});
I can provide any extra clarification quickly. Thanks!
EDIT: The question is that executing this sort for large list takes several seconds. In my core2duo it might take up to 20 seconds! I changed the find(".english") to filter(".english") and the speed seems to be the same. Any idea on how to speed that up?
Upvotes: 0
Views: 2865
Reputation: 25371
I think if you add name as metadata to the node and eliminate looking through the DOM on every comparison, it'll be much faster. Remember, there's O(n2) of them after all.
$(function() {
$('.media-status-specie li')
.each(function () {
$(this).data('name', $(this).find(".english").text());
})
});
....
function sortDescending1(a, b) {
return $(a).data('name') < $(b).data('name') ? 1 : -1;
}
Disclaimer: It's my opinion, I'm no good at guessing slow points as any other developer out there, use profiler to find real performance killer.
Upvotes: 1
Reputation: 5027
Make a copy in memory of the list and sort it, then replace the existing list with the sorted one. That would be faster than manipulating live, visible, DOM elements.
Upvotes: 2