【问题标题】:Chrome: Why change style in batch(cssText) is slower then change in single(.style.property) way?Chrome:为什么批量更改样式(cssText)比单个更改(.style.property)方式慢?
【发布时间】:2013-12-19 10:10:18
【问题描述】:

High Performance Javascript 书中,我读到了关于最小化重绘和回流的文章,批量 DOM 更改可以带来更好的性能,例如使用:

var el = document.getElementById('mydiv');
el.style.cssText = 'border-left: 1px; border-right: 2px; padding: 5px;';

而不是

var el = document.getElementById('mydiv');
el.style.borderLeft = '1px';
el.style.borderRight = '2px';
el.style.padding = '5px';

我在 Chrome 中做了一个测试,但结果相反,这是我的测试代码:

var ie = (function(){
    var undef, v = 3, div = document.createElement('div');

    while (
        div.innerHTML = '<!--[if gt IE '+(++v)+']><i></i><![endif]-->',
        div.getElementsByTagName('i')[0]
    );

    return v> 4 ? v : undef;
}());


// First insert 100*100 element

var total = 100 * 100;
var round = 100 * 100;

var body = document.querySelector("body");

if (ie) {
    total = round = 100 * 10;       
}

var createElement = function (id) {
    var div = document.createElement("div");
    div.setAttribute("id", "id-" + id);
    return div;
}

for (var i = 0; i <= total; i++) {
    body.appendChild(createElement(i));
}

// Then change style in random
function randomFromInterval(from, to) {
    return Math.floor(Math.random() * (to-from+1)+from);
}

function randomWidth() {
    return randomFromInterval(0, 200) + "px";
}

function randomHeight() {
    return randomFromInterval(0, 200) + "px";
}

function randomColor() {
    var r = randomFromInterval(0, 255),
        g = randomFromInterval(0, 255),
        b = randomFromInterval(0, 255);

    return "rgb(" + r + ", " + g + ", " + b + ")";
}

var time = +new Date();

for (var i = 0; i <= round; i++) {
    var id = randomFromInterval(0, total);
    var div = document.querySelector("#id-" + id);

    // The `slower` way...but it is faster, use less time
    div.style.width = randomHeight();
    div.style.height = randomWidth();
    div.style.backgroundColor = randomColor();

    // var text = "width: " + randomWidth() + "; height: " + randomHeight() + "; background: " + randomColor() + ";"
    // div.style.cssText = text;
}

console.log(+new Date() - time);

这是我的演示:

http://jsfiddle.net/9BV5E/

http://jsfiddle.net/9BV5E/1/

第一个我使用.style.方式,第二个使用cssTest方式;

而且我也在IE8中测试过,两种方式的时间差不多。

那本书有错吗?还是有其他原因?

【问题讨论】:

    标签: javascript css google-chrome performance-testing


    【解决方案1】:

    请问你是如何测试这个的?

    您是否将测试用例输入到 jsperf.com a la these

    可用信息全面表明cssText is better when setting multiple styles vs individual ones,在执行测试时,我似乎无法复制您注意到的结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 2020-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-23
      • 1970-01-01
      相关资源
      最近更新 更多