Attribute vs Class selection

JavaScript performance comparison

Revision 3 of this test case created by Miloš Rašić

Preparation code

<ul>
<li id="1" data-cargroup="A" class="js-CarGroup-A">A</li>
<li id="2" data-cargroup="B" class="js-CarGroup-B">B</li>
<li id="3" data-cargroup="C" class="js-CarGroup-C">C</li>
<li id="4" data-cargroup="C" class="js-CarGroup-C">C</li>
<li id="5" data-cargroup="D" class="js-CarGroup-D">D</li>
</ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    

Preparation code output

<ul> <li id="1" data-cargroup="A" class="js-CarGroup-A">A</li> <li id="2" data-cargroup="B" class="js-CarGroup-B">B</li> <li id="3" data-cargroup="C" class="js-CarGroup-C">C</li> <li id="4" data-cargroup="C" class="js-CarGroup-C">C</li> <li id="5" data-cargroup="D" class="js-CarGroup-D">D</li> </ul>

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Data-attribute selection
$('li[data-cargroup = "C"]');
pending…
Class-based selection
$('li.js-CarGroup-C');
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.

1 Comment

Miloš Rašić (revision owner) commented :

I think the slight advantage in favour of selection by class comes from the fact that jQuery has to do more in order to parse the attribute selector which is far more complicated than the class selector. Both classes and attributes seem to be stored in the DOM as maps by js implementations.