Performance boost when using multiple $ and _

Performance boost when using multiple $ and _

tpctpc Posts: 12Questions: 0Answers: 0
edited January 2013 in General
Just wanted to share a speed improvement that I made to some of my code that others might find useful. I created a custom menu that required five calls to $ and/or _ to return the state of each row. This proved to be a showstopper in IE because all the looping within $ and _ brought it to its knees.

Rather than making 5 calls using $ and _ I cut it down to 2 and then leveraged the jQuery .filter to find what I needed. Now all browsers are happy happy happy (Phil Robertson TM).

Hope that someone else will find this useful.

The .row_selected and .unselectable are just css classes that may or may not be applied to each row

This
[code]
var selectedRows = this.$('tr.row_selected').not('tr.unselectable').length;
var filteredRows = this.$('tr', { "filter": "applied" }).length;
var selectedFilteredRows = this.$('tr.row_selected', { "filter": "applied" }).not('tr.unselectable').length;
var unselectableRows = this._('tr.unselectable').length;
var unselectableFilteredRows = this._('tr.unselectable', { "filter": "applied" }).length;
[/code]

Became this

[code]
var allRows = this.$('tr');
var allFilteredRows = this.$('tr', { "filter": "applied" });

var selectedRows = allRows.filter('.row_selected:not(.unselectable)').length;
var unselectableRows = allRows.filter('.unselectable').length;
var filteredRows = allFilteredRows.length;
var selectedFilteredRows = allFilteredRows.filter('.row_selected:not(.unselectable)').length;
var unselectableFilteredRows = allFilteredRows.filter('.unselectable').length;
[/code]

Replies

  • allanallan Posts: 63,523Questions: 1Answers: 10,473 Site admin
    Very nice :-).

    I think the general jQuery premise of caching selectors also applies to using the `$` and `_` API methods that DataTables exposes. If you don't need to query the whole table again, don't.

    Thanks for sharing this with us!

    Allan
This discussion has been closed.