Inspired by chapter 7 of Learning jQuery 1.3 (not found in the third edition), I’ve put together this sort routine:
var rows = $table.find('tbody > tr').get();
$.each(rows, function(index, row) {
var $cell = $(row).children('td').eq(column);
$(row).data('sortKey',$cell);
});
rows.sort(function(a, b) {
if ($(a).data('sortKey') < $(b).data('sortKey'))
return -sortDirection;
if ($(a).data('sortKey') > $(b).data('sortKey'))
return sortDirection;
return 0;
});
But I don’t like using $(a) and $(b) on every row.
Q: Is there a way I can cache $(a) and $(b)? The author uses something he calls an expando instead.
This kind of property, attached to a DOM element but not a normal DOM
attribute, is called an expando. This is a convenient place to store
the key, since we need one per table row element. Now, we can examine
this attribute within the comparator function, and our sort is
markedly faster.
There are two optimisations you can do here.
The first is to use
$.datarather than$.fn.data:This is superior because it does not need to construct a new jQuery object — you are right to think of this as a performance issue.
The second is to cache the result of
data, so you only need to do it once.The third optimisation (since a lonesomeday answer is buy-two-get-one-free) is to use jQuery 1.7, which is much superior to 1.3, both in speed and in other functionality.