2010年10月2日星期六

optimize jquery selector

var items = '
    ';
    for (i=0; i<1000; i++) {
    items += '
  • item
  • ';
    }
    items += '
';


var list = $('#list');
list.html(items);


console.time('direct');
for (i=0; i<10000; i++) {
var s = $('.item');
}
console.timeEnd('direct');
console.time('Specific tag');
for (i=0; i<10000; i++) {
var s = $('li.item');
}
console.timeEnd('Specific tag');
console.time('Specific class');
for (i=0; i<10000; i++) {
var s = $('.item.anotherClass');
}
console.timeEnd('Specific class');
console.time('Specific another class');
for (i=0; i<10000; i++) {
var s = $('li.item.anotherClass');
}
console.timeEnd('Specific another class');

console.time('with ancestor');
for (i=0; i<10000; i++) {
var s = $('#ulId .item');
}
console.timeEnd('with ancestor');

console.time('with context');
for (i=0; i<10000; i++) {
var s = $('.item','#ulId');
}
console.timeEnd('with context');
console.time('specific tag with context');
for (i=0; i<10000; i++) {
var s = $('.item','#ulId');
}
console.timeEnd('specific tag with context');

console.time('direct with jquery context');
for (i=0; i<10000; i++) {
var s = $('.item',$('#ulId'));
}
console.timeEnd('direct with jquery context');

得出
direct: 3791ms
Specific tag: 3483ms
Specific class: 4128ms
Specific another class: 3001ms
with ancestor: 3094ms
with context: 72ms
specific tag with context: 73ms
direct with jquery context: 75ms


最緊要係加context!