Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery : which is faster in this case (.find) vs (.filter) [closed]

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?

like image 473
Thanh Trung Avatar asked Jun 13 '13 12:06

Thanh Trung


People also ask

Which of this function is faster in jQuery?

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...

Which loop is faster in jQuery?

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!

What is the difference between filter and find?

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.

What is difference between grep and filter in jQuery?

The grep() method finds an element and the filter() method returns elements matching a specific criteria.


1 Answers

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.

like image 80
James Donnelly Avatar answered Oct 08 '22 00:10

James Donnelly