I have a big table, containing lots of lines (50-200) and columns (30). So in total I have at least 1500 cells. I want to know which of the following instructions are faster and why?
//assuming we have some predefined variable
var table = $('#myTable');
var allCells = table.find('td');
If a selected cell have a class selected
selectedCells = table.find('td.selected');
vs
selectedCells = allCells.filter('.selected');
Or is there a better, native javascript way (in term of performance and readability) to find selected cells considering you have 1500 cells to loop through?
Nearly all plain Javascript functions will be faster than jQuery operations. This is because jQuery has overhead in creating a jQuery object in order to be more flexible, allow for chaining, support collections, etc...
each() loop : Lower performance compare to other loops (for games/animations/large datasets) Less control over iterator (skip items, splice items from list, etc). Dependency on jQuery library unlike for, while etc loops!
The find() method is used to find all the descendant elements of the selected element. It finds the element in the DOM tree by traversing through the root to leaf. The filter() method is used to filters all the elements and returns the element that matches and the element that do not match are removed.
The grep() method finds an element and the filter() method returns elements matching a specific criteria.
find()
here will be faster as your filter()
method relies on find()
anyway. From your code:
var allCells = table.find('td');
selectedCells = allCells.filter('.selected');
table.find('td.selected');
pulls only the td
elements with the selected
class.
table.find('td').filter('.selected')
pulls all the td
elements then filters only the elements with the selected
class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With