views:

718

answers:

4

Hello, What is better from performance wise document.getElementById('elementId') or $('#elementId') ? How can I calculate the speed by myself?

Thank you and Kind Regards.

+15  A: 

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.

Marius
+1. Also, the speed difference depends on how you use it. If it just a single call to either one of them, there will hardly be any difference. If the call is made hundreds or thousands of times inside a loop or recursively or something, you might notice that jQuery selector is a bit slower.
Senthil
+1  A: 

Of course getElementById is faster but with jQuery you can do lots of things.

To test that, you can try to loop 10k times for each, and compare timestamps before and after.

S.Mark
+3  A: 

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.

console.profile();
$('#eleId');
console.profileEnd();
redsquare
+8  A: 

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 :

$( document.getElementById("some_id") ).jQueryCall();

This will give you a better performance, and at the same time, allow you to use jQuery.

jeffreyveon