3 ms·
The kind of chaining shown in slide 97 feels dirty. Is end() faster than calling $('div.entry') again?
by natrius 19y ago
The kind of chaining shown in slide 97 feels dirty. Is end() faster than calling $('div.entry') again?
- simonw 19y agoI can't imagine there's a noticeable speed difference between the two, but .end() is more about avoiding code duplication than speeding things up. If you don't like it, you can use a variable instead: var entries = $('div.entry').css('border', '1px solid black'); entries.find('a').css('color', 'red'); entries.find('p').addClass('p-inside-entry'); I was initially pretty skeptical about chaining - I didn't find it easy to read, and I was worried that it would mean bugs in the middle of a chain were hard to spot. In practice I've found that these concerns were unfounded - chaining is perfectly readable once you get used to it (provided you don't go too crazy) and it's trivial to split a chain in to separate chunks if you need to debug it.
- natrius 19y agoMy concern isn't really with it causing bugs in my code; it's more with trying to decipher other people's code and making their lives easier when they have to read mine. I was skeptical about chaining at first too, but it all seems nice except for .end(). The speed question is because I don't know how jQuery actually goes about selecting elements. For example, with 'div.entry', I presume it does something like a getElementsByTagName('div'), then iterates through those to find the ones that have class 'entry'. If jQuery stores that somewhere and .end() has some sort of magic to get the precomputed list back that $() itself doesn't, I thought it might be slower. The method you showed avoids that, but at the cost of precious, precious keystrokes. I guess I'll just poke around in the code at some point to see what's going on.