jQUery Selectors vs Native API

JavaScript performance comparison

Revision 25 of this test case created

Preparation code

<div id="testid"></div>
<div class="testclass"></div>

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<script>
 var regex = /[=#@.*]/g;

function newQuerySelectorAll (querySelector){
        var matches = querySelector.match(regex),
            selection, firstChar, tempElm;
        if(matches.length > 0){
            if(matches.length > 1){
                selection = document.querySelectorAll(querySelector)
            } else{
                firstChar = querySelector.charAt(0);
                if(firstChar === "."){
                    selection = document.getElementsByClassName(querySelector.slice(1))
                } else if(firstChar === "#"){
                    //getElementById doesn't return an HTMLCollection, therefore we have to jump through some hoops to make one.
                    var dummyElm = document.createElement("div");
                    if(tempElm = document.getElementById(querySelector.slice(1)))
                        dummyElm.appendChild(tempElm);
                    selection = dummyElm.children;
                } else{
                    selection = document.querySelectorAll(querySelector)
                }
            }
        } else{
            selection = document.getElementsByTagName(querySelector);
        }

        return selection;
    };
</script>
 

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
jQuery ID Selector
$("#testid");
pending…
getElementById
document.getElementById("testid");
pending…
jQuery class Selector
$(".testclass");
pending…
Native querySelector
document.querySelector(".testclass");
pending…
Create jQuery from Native
newQuerySelectorAll('#testid');
pending…
Native querySelector to jQuery Object
document.querySelectorAll('#testid');
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment