What is better from performance wise document.getElementById('elementId')
or $('#elementId')
?
How can I calculate the speed by myself?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to fix IE ClearType + jQuery opacity problem i
- void before promise syntax
- jQuery add and remove delay
Since the other performance test that was linked in this page seemed to be broken, and it also included something that wasn't asked about in this question (namely a custom jQuery method), then I decided to make a new performance benchmark to answer the question which includes the exact equivalent (returns the DOM element) in jQuery, instead of a custom method:
https://jsperf.com/jquery-get-0-vs-get-element-by-id
When I run it in my Chrome, it shows that a straight jQuery
is 92% slower than the equivalent operation in standard JavaScript
I also tried out what is currently marked as the accepted answer here, which supposedly "much much faster" but it is still 89% slower than the standard JavaScript equivalent:
Feel free to run it for yourself and see what you get in your browser, with the performance benchmark that I made. The version with no jQuery seems to be a lot faster.
If you are concerned about performance, native getElementById is much much faster, but jQuery gives you very handy access to a lot of stuff. So, you might want to use something like :
This will give you a better performance, and at the same time, allow you to use jQuery.
getElementById is faster, because it uses native code. The jQuery selector will also use getElementById, but it first needs to do a lot of tests and comparisons on the text.
The native getElementById is faster. Jquery selector engine just wraps this for any #x selectors.
Using the firebug console you can profile jquery in the following way. Not sure it works well for native api calls like getElementById.
Use http://jsperf.com/ if you want to test any kind of performance between jquery and dom but jquery is normaly slower with everything since it is based on the dom.
I've just stumbled upon this post whilst wondering the same question... so decided to knock up a quick test script... run it, try it yourself, blew my mind!
After running this script, I got the following results:
Run 1
With
$(document.getElementById("test")).somejQueryCall()
: 552 millisecondsWith
$("#test").somejQueryCall()
: 881 millisecondsWith
$(elem).somejQueryCall()
: 1317 millisecondsRun 2
With
$(document.getElementById("test")).somejQueryCall()
: 520 millisecondsWith
$("#test").somejQueryCall()
: 855 millisecondsWith
$(elem).somejQueryCall()
: 1289 millisecondsRun 3
With
$(document.getElementById("test")).somejQueryCall()
: 565 millisecondsWith
$("#test").somejQueryCall()
: 936 millisecondsWith
$(elem).somejQueryCall()
: 1445 millisecondsI can't believe the difference!!! Just had to share this!
Peace!