在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);
这是我的演示:
第一个使用.style.
方式,第二个使用cssTest
方式;
我也在IE8中测试它们,双向的时间几乎相同。
这本书错了吗?还是有其他原因?
答案 0 :(得分:2)
请问您是如何测试的?
您是否已将测试用例输入jsperf.com la these?
可用信息全面显示cssText is better when setting multiple styles vs individual ones,在执行测试时,我似乎无法复制您注意到的结果。