Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is more efficient - $('selector').last() or $('selector:last')?

I have a parent element with a real lot of child elements (1000s). I am looking for the fastest possible way to get a handle to the last child element. The options I've found are:

$('.parent .child').last()

and

$('.parent .child:last')

Any opinions on which one is reliably faster across browsers?

EDIT

I wrote a test in jsfiddle to measure this out and it turns out the difference is pretty much negligible. Though .last() was performing better, the difference is negligible. So i think even with the :last selector, it is actually getting the whole list of elements and then returning the last element? Unbelievable.

Fiddle: http://jsfiddle.net/techfoobar/GFb9f/8/

like image 825
techfoobar Avatar asked Aug 31 '12 05:08

techfoobar


2 Answers

Many modern browsers support document.querySelectorAll(), so $('.parent .child').last() should be faster, as the selector string can be passed as is, and then the last matched item popped off.

In the latter, the :last is not a standard pseudo selector, and Sizzle has to start chunking the selector string to start matching.

Overall though, I would use what you believe is the most readable. To begin optimising this, first ensure that your application has performance issues and you have identified this selector as the bottleneck.

like image 51
alex Avatar answered Oct 14 '22 03:10

alex


You have to see this performance test!

UPDATE: There are already good answers on this related question.

like image 22
Robin Maben Avatar answered Oct 14 '22 04:10

Robin Maben