我怎样才能提高我下面的 JQuery 代码的性能:
var firstRowCellsWidth = new Array();
function initialize();
$('table.rgMasterTable > tbody > tr:first > td').each(function () {
firstRowCellsWidth.push({
normalCellWidth: $(this).width(),
firstTemplateCellWidth: $(this).find('table > tbody > tr > td:first').width()
});
});
}
我正在使用 :first
、$(this)
、.find(, >
和 each()
。这些显然会降低性能?
应该用什么代替?或者它们等效的 native javascript 代码是什么?
我猜想使用 for 循环而不是 each()
方法。剩下的呢?
代码的目的: 计算出表格每一列的宽度。可以看出,主表还有一个嵌套表。
谢谢,
最佳答案
var firstRowCellsWidth = [];
function initialize(){
var tables = document.getElementsByTagName("table");
for(var i=0; i<tables.length; i++){
if(/(^|\s)rgMasterTable(\s|$)/.test(tables[i].className)){
//a className is only valid if the className is contained within a space/nothing(^) and a space/nothing($)
var tcell = tables[i].rows[0].cells; //Any cell
for(var j=0; j<tcell.length; j++){
firstRowCellsWidth.push({
normalCellWidth:tcell[j].offsetWidth,
firstTemplateCellWidth:tcell[j].getElementsByTagName("td")[0].offsetWidth
//the first cell of any row of any table = the first occurence of a TD element
});
}
//break;
//Uncomment the previous line if you want to enumerate through all tables whose class equals .rgMasterTable
}
}
}
在不使用 JQuery 的情况下尽可能高效(懒惰的脚本编写者经常使用框架,他们不介意计算效率的损失)。
请注意,当文档结构与您的描述不匹配时会抛出错误 (tcell[j].getElementsByTagName("td"[0] is undefined
)。
编辑:JavaScript 与 JQUery 的速度对比
作为对 maxedison(第三条评论)的回应,他质疑我关于 JQuery 的效率低于 JavaScript 的说法。复制下面的代码片段并将它们粘贴到(本页的)地址栏中。将出现一个提示,其中可以指定测试的数量。测试运行后,会弹出一个警报,显示执行这些测试所需的毫秒数。提供了两个测试用例:
原生 JavaScript 测试用例:
javascript:alert((function(m){
for(var i=0, t=new Date; i<m; i++){
document.getElementsByTagName("table")[0].rows[0].cells[0];
}
return (new Date).getTime()-t.getTime();
})(prompt("Native\x20JS,\x20repeat\x20n\x20times:","10000")));
JQuery 测试用例。警告:不要从大量测试开始:
javascript:alert((function(m){
for(var i=0, t=new Date; i<m; i++){
$("table > tbody > tr > td:first");
}
return (new Date).getTime()-t.getTime();
})(prompt("JQuery,\20repeat\x20n\x20times","10")));
在我 1 岁的笔记本电脑上,使用 FireFox 3.6.22,使用原生 JavaScript 的 10000 次调用等于 5 次 JQuery 执行。
关于jquery - 如何用更高性能的等效函数替换 .each() 和 .find() 等 JQuery 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7388953/