问题描述
我是一个jQuery noob,试图跟踪我们在使用大表时遇到的性能问题.我们有一个本地化的表格小部件,除其他外,该部件将列的宽度设置为标题宽度或行宽度的最大值.
I'm a jQuery noob trying to track down a performance issue that we're having with large tables. We have a homegrown table widget which, among other things, sets the column widths to the max of the header width or the rows width.
对于具有10行乘500列的表,这可能要花费将近40秒(!),因为该表可以在不到一秒钟的时间内呈现出来.
With a table of 10 rows by 500 columns, this can take almost 40 seconds (!) which seems excessive given that the table can be rendered in under a second.
这是整个功能:
var dataTable = this._div.find('.data-table');
var headerTable = this._div.find('.data-header-table');
if (dataTable.length === 0 || headerTable.length === 0) {
return;
}
dataTable = dataTable[0];
headerTable = headerTable[0];
if (dataTable.rows.length === 0) {
return;
}
var dataTr = dataTable.rows[0];
var headerTr = headerTable.rows[headerTable.rows.length - 1];
var marginColumnWidths =
$(dataTr.cells[0]).outerWidth(true) +
$(dataTr.cells[1]).outerWidth(true) +
$(dataTr.cells[2]).outerWidth(true) -
DOM.getHPaddings($(headerTr.cells[0])) + 1;
$(headerTable)
.find('> tbody > tr > td:first-child')
.width('1%')
.children()
.first()
.width(marginColumnWidths);
for (var i = 1; i < headerTr.cells.length; i++) {
var headerTd = $(headerTr.cells[i]);
var dataTd = $(dataTr.cells[i + 2]);
var commonWidth = Math.max(
Math.min(headerTd.width(), 100),
dataTd.width()
);
headerTd.width('1%').find('> div').width(commonWidth);
dataTd.children().first().width(commonWidth);
}
如果我替换
var commonWidth = Math.max(
Math.min(headerTd.width(), 100),
dataTd.width()
);
带有常量
var commonWidth = 100;
执行时间从38秒减少到一秒以下,表明问题出在读取/计算当前宽度,而不是设置新宽度.从我完成的性能分析/采样中,看来jQuery花费了过多的时间来处理CSS计算.
the execution time drops from 38 seconds to under a second, indicating that the issue is on reading/calculating the current widths as opposed to setting the new width. From the profiling/sampling that I've done, it appears that jQuery is spending an inordinate amount of time messing around with CSS calculations.
有人可以推荐一种更有效的方法吗?
Can anyone recommend a more efficient way to do this?
我尝试了css("width")和externalWidth(),而性能没有任何重大变化.我们使用的是jQuery 1.7.2,但是升级到1.8.1并没有明显改变性能.
I've tried both css("width") and outerWidth() without any significant changes in performance. We were using jQuery 1.7.2, but upgrading to 1.8.1 didn't change performance significantly.
推荐答案
使用.css("width")
代替.width()
,对.width()
方法进行了更改,使其运行速度变慢.请阅读以下内容以获取更多信息: http://blog.jquery.com/2012/08/16/jquery-1-8-box-sizing-width-csswidth-and-outerwidth/
Use .css("width")
instead of .width()
, changes were made to the .width()
method that make it perform slower. Read this for more information: http://blog.jquery.com/2012/08/16/jquery-1-8-box-sizing-width-csswidth-and-outerwidth/
var commonWidth = Math.max(
Math.min(parseFloat(headerTd.css("width")), 100),
dataTd.width()
);
这篇关于jQuery width()方法的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!