Improving jQuery code performance

Following jQuery performance related articles here is another tip to boost your jQuery code performance. You should use ID selections whenever you can. Because jQuery uses browser's native getElementById() function which is much faster.

Now back to JavaScript code performance testing. I have an unordered list with 1000 items. First test will have list items with class attributes and the second list will have id attributes set to its items.

console.time('test');  
for (i = 0; i < 500; i++) {  
    $('.'+i);  
}  
console.timeEnd('test'); 
// ~8204ms 

console.time('test');  
for (i = 0; i < 500; i++) {  
    $('#'+i);  
}  
console.timeEnd('test'); 
// ~32ms

As you can see selecting with element's #id is much faster. In our case 256 times (8204/32).