Performance of jquery selectors vs css3 selectors

2019-05-05 07:30发布

问题:

I am fairly new to css3 using selectors (or simple css selectors in general) and am curious about the performance comparison of these css selectors vs jquery or javascript selectors?

Say you have something like this:

css version

#someID > div:nth-child(2n) { some css .... }

jquery version (edit)

$("#someID").children(":nth-child(even)").css({ some css ....});

Is it often faster to use the css selectors whenever you can, or use jquery selectors to adjust the css involved with an element or set of elements? Mainly when the set gets rather large. I would assume there wouldn't be much performance difference with only a handful of items?

Thanks!

回答1:

jQuery's selector engine shares most of the same syntax as CSS, effectively extending the selector standard. This means you can pass most valid CSS selectors (with some exceptions) to jQuery and it'll handle them just fine.

jQuery optimizes valid CSS selectors for modern browsers that support the selectors API by passing them directly to document.querySelectorAll(). This means your jQuery selector will have almost equal performance with the equivalent CSS selector, with the only overhead being the $().css() and the selectors API calls.

For browsers that don't support the selectors API, well, it's pretty obvious that jQuery will be really slow as it has to do all the heavy lifting on its own. More importantly, it will simply fail on the exceptions that I link to above as well as any other CSS selectors a browser doesn't support.

However, with all that said, jQuery will invariably be slower, as the browser has to run through a script and evaluate it before getting a chance to apply and compute your styles.

And after all this, honestly, it's not much even if you had hundreds of items — chances are the browser is going to take longer to fetch the markup than to render the styles. If you need to do styling, and CSS supports it, why not use CSS? That's why the language was created in the first place.



回答2:

Pure CSS will always be faster since it's done within the browser and optimized!

The downside is that some selectors might not be supported by the browser you're on. See http://caniuse.com/#feat=css-sel3



回答3:

For me if I use jquery means that I want to put some effect on it, say like

$("#someID:nth-child(even)").css({ some css ....}).fadeIn('slow');

Apart from that you better use CSS itself, but we are barely to see the difference of it anyway, at least for a small scope system.

I've found this web that compare selector capability from different javascript framework and jquery does it quite well.

javascript framework selector test