selector: class vs id

JavaScript performance comparison

Test case created

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div id="myList"></div>
<script>
Benchmark.prototype.setup = function() {
    var $myList = $('#myList');  
    var myListItems = '<ul>';  
    for (i = 0; i < 1000; i++) {  
         myListItems += '<li id="listItem' + i + '" class="listItem' + i + '">This is a list item</li>'; //这里使用的是class  
     }  
    myListItems += '</ul>';  
    $myList.html(myListItems);  
};
</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
class
$('.listItem' + i);
pending…
id
$('#listItem' + i); 
pending…

You can edit these tests or add even more tests to this page by appending /edit to the URL.

Compare results of other browsers

0 comments

Add a comment