jQuery width()方法的性能

Tom*_*ris 2 performance jquery

我是一个jQuery noob试图追踪我们对大表的性能问题.我们有一个自制的表小部件,除其他外,它将列宽设置为标题宽度或行宽的最大值.

使用10行乘500列的表,这可能需要将近40秒(!),这似乎是过分的,因为表可以在一秒钟内呈现.

这是整个功能:

  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);
  }
Run Code Online (Sandbox Code Playgroud)

如果我更换

    var commonWidth = Math.max(
      Math.min(headerTd.width(), 100),
      dataTd.width()
    );
Run Code Online (Sandbox Code Playgroud)

不变的

    var commonWidth = 100;
Run Code Online (Sandbox Code Playgroud)

执行时间从38秒下降到不到一秒,表明问题在于读取/计算当前宽度而不是设置新宽度.从我所做的分析/抽样看来,似乎jQuery花费了大量的时间搞乱CSS计算.

任何人都可以推荐一种更有效的方法吗?

编辑:

我已经尝试了css("width")和outerWidth(),但性能没有任何重大变化.我们使用的是jQuery 1.7.2,但升级到1.8.1并没有显着改变性能.

use*_*654 9

使用.css("width")替代方法,对使其执行较慢.width().width()方法进行了更改.阅读本文以获取更多信息: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()
);
Run Code Online (Sandbox Code Playgroud)

  • 嗯.测试过这个.与我建议的方法相比.出现差异不大.以下是测试:[宽度一个循环](http://jsperf.com/width-test),[css width one loop](http://jsperf.com/width-test-2),[css两个循环] (http://jsperf.com/width-test-3),[width two loops](http://jsperf.com/width-test-4).结果 - 几乎没有区别.最慢 - "宽度"一个循环.最快 - 其中一个有`css`.不时不同.**注意:**四种不同的测试与on case因为看起来像js perf不能清除测试用例之间的html状态. (3认同)