我有一些代码循环并调用一个在表上进行某些计算的函数。我痛苦地经历了大量的代码来确定这个特定代码是导致chrome冻结大约一分钟的原因。有没有人对如何从性能角度改进此代码有任何建议?
function getAverage(a, b) {
var sum = 0;
var count = 0;
$(a).each(function () {
$content = $(this).html();
var tdTxt = parseFloat($(this).text(), 10) || 0;
if ($(this).hasClass(b)) {
var theAvg = parseFloat((sum / count), 10) || 0;
$(this).text(theAvg.toFixed(2));
sum = 0;
count = 0;
} else {
sum += parseFloat(tdTxt);
if ($content == '') {
}
else {
count += 1;
}
}
})
}
var el1 = $('#rackPlan1 > thead > tr > th:gt(17):not(.totalRow)');
var starter = 19;
for (i = 0; i < el1.length; i++) {
$('#rackPlan1 > tbody > tr > td:nth-child(' + starter + ')').each(function () {
getAverage('#rackPlan1 > tbody > tr > td:nth-child(' + starter + ')', 'subTotal');
})
starter += 1;
}
非常感谢
答案 0 :(得分:0)
严格查看getAverage()
函数,我建议:
function getAverage(a, b) {
var $this, $content, tdTxt, theAvg; // it's marginally less expensive to declare vars at a higher scope and re-use them in a lower scope
var sum = 0;
var count = 0;
$this = $(a); // cache this nth-child received from the $.each loop
$content = $this.html();
tdTxt = parseFloat($this.text(), 10) || 0;
if ($this.hasClass(b)) {
theAvg = parseFloat((sum / count), 10) || 0;
$this.text(theAvg.toFixed(2));
sum = 0;
count = 0;
} else {
sum += parseFloat(tdTxt);
if ($content == '') {
}
else {
++count; // this micro-optimization makes it marginally faster
}
}
}
查看另一块代码:
var el1 = $('#rackPlan1 > thead > tr > th:gt(17):not(.totalRow)');
var starter = 19;
$('#rackPlan1 > tbody > tr > td:nth-child(' + starter + ')').nextUntil(':nth-child(' + ((starter+el1.length)-1) + ')').each(function(){
getAverage(this, 'subTotal');
});
我在[{1}}中没有经验丰富,所以这可能会更好吗?
:nth-child
如果$('#rackPlan1 > tbody > tr > td:nth-child(' + starter + 'n+' + ((starter+el1.length)-1) + ')').each(function(){
getAverage(this, 'subTotal');
});
内容失败,则只需尝试替换:
nth-child
与
getAverage('#rackPlan1 > tbody > tr > td:nth-child(' + starter + ')', 'subTotal');