我已经获得了一些用于测试jQuery选择器性能的代码。我在浏览器控制台中以100000次重复运行测试3次。第一次测试始终是最慢的,然后,以下两项速度几乎相等。有谁知道为什么?
这里是小提琴:http://jsfiddle.net/05xq70na/,执行时间记录在浏览器控制台中。
var repetitions = 100000;
var html = '<ul><li id="parent"><div id="child" class="child" value="test"></div></li></ul>';
var time = [];
var finished = false;
var tests = {
"SelectorById": function(){
var element;
element = $("#child");
},
"SelectorByClass": function(){
var element;
element = $(".child");
},
"SelectorByTag": function(){
var element;
element = $("li");
}
}
function showResults(loopCounter) {
if(!finished) {
finished = true;
console.log("\nResults (" + loopCounter + " repetitions):");
for(executionTime in time) {
console.log(executionTime + ": " + (time[executionTime] / loopCounter) + " ms");
}
}
}
function perform(test, string) {
var startTime,
endTime,
nextTest = tests[test];
if(time[test + string] === undefined) {
time[test + string] = 0;
}
startTime = performance.now();
nextTest();
endTime = performance.now();
time[test + string] += (endTime - startTime);
}
function benchmark(tests) {
for(var i=0, loopCounter=1; i<repetitions; i++) {
// console.log('repetition ' + loopCounter);
for(test in tests) {
// console.log('\texecute ' + test);
perform(test, "1");
perform(test, "2");
perform(test, "3");
}
loopCounter++;
if(loopCounter>repetitions) {
showResults(--loopCounter);
};
}
}
document.getElementsByTagName('body')[0].innerHTML = html;
benchmark(tests);