我正在尝试测试缓存我的 DOM 选择(将选择分配给 var)在我的旧 JS 代码上的执行情况。我尝试使用 JSPerf,但它似乎只是在循环中运行所有内容,这意味着我的 var 分配被重复了数千次。我怎样才能解决这个问题?
JSFiddle用于我更新的代码
基准测试脚本(旧代码)#1:
$('.projectscontainer').on("click", "span.destproject", function () {
$(this).siblings('.projectschildren').toggle().end().siblings('div.destarrow').toggleClass("arrow-right arrow-down");
}).on("click", "div.destarrow", function () {
$(this).parent().find("span.destproject").trigger("click");
});
$('body').on("click", "span#expandcollapse", function () {
if ($(this).text() === 'Expand All') { //Currently collapsed
var startTime = new Date().getTime();
$('.projectscontainer').find("div.destarrow").filter('.arrow-right').toggleClass("arrow-right arrow-down");
$('.projectscontainer').find(".projectschildren").toggle(true);
var endTime = new Date().getTime();
console.log('Action took: ' + (endTime - startTime) + 'ms');
} else { //Currently expanded
var startTime = new Date().getTime();
$('.projectscontainer').find("div.destarrow").filter('.arrow-down').toggleClass("arrow-down arrow-right");
$('.projectscontainer').find(".projectschildren").toggle(false);
var endTime = new Date().getTime();
console.log('Action took: ' + (endTime - startTime) + 'ms');
}
$(this).text(function (i, currentText) {
return currentText === 'Expand All' ? 'Collapse All' : 'Expand All';
});
});
基准测试脚本(新代码)#2:
var projectscontainer = $('body').find('div.projectscontainer');
var projectschildren = projectscontainer.find("div.projectschildren");
var destarrows = projectscontainer.find("div.destarrow");
var srcprojects = projectscontainer.find("div.srcprojects");
projectscontainer.on("click", "span.destproject", function (){
$(this).siblings('div.projectschildren').toggle().end().siblings('div.destarrow').toggleClass("arrow-right arrow-down");
}).on("click", "div.destarrow", function (){
$(this).parent().find("span.destproject").trigger("click");
});
$('body').on("click", "#expandcollapse", function (){
if($(this).text() === 'Expand All'){//Currently collapsed
var startTime = new Date().getTime();
destarrows.filter('div.arrow-right').toggleClass("arrow-right arrow-down");
projectschildren.toggle(true);
var endTime = new Date().getTime();
console.log('Action took: ' + (endTime - startTime) + 'ms');
} else {//Currently expanded
var startTime = new Date().getTime();
destarrows.filter('div.arrow-down').toggleClass("arrow-down arrow-right");
projectschildren.toggle(false);
var endTime = new Date().getTime();
console.log('Action took: ' + (endTime - startTime) + 'ms');
}
$(this).text(function(i, currentText){
return currentText === 'Expand All' ? 'Collapse All' : 'Expand All';
});
});
JSPerf 基准测试最终会运行这些行
var projectscontainer = $('body').find('div.projectscontainer');
var projectschildren = projectscontainer.find("div.projectschildren");
var destarrows = projectscontainer.find("div.destarrow");
var srcprojects = projectscontainer.find("div.srcprojects");
一遍又一遍(连同所有其他代码),而在我的原始代码中,它只运行一次。如何让它只运行一次而不是重复运行?