I recently came across some interesting tips in the "High Performance Javascript" book regarding optimizing for minimizing repaints and reflows. One of the suggestions was to batch DOM changes for better performance, such as utilizing:
var el = document.getElementById('mydiv');
el.style.cssText = 'border-left: 1px; border-right: 2px; padding: 5px;';
as opposed to
var el = document.getElementById('mydiv');
el.style.borderLeft = '1px';
el.style.borderRight = '2px';
el.style.padding = '5px';
Intrigued by this, I decided to conduct a test in Chrome to verify the claim. Here is the code snippet I used for testing:
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 randomly
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 surprisingly faster
div.style.width = randomHeight();
div.style.height = randomWidth();
div.style.backgroundColor = randomColor();
}
console.log(+new Date() - time);
Here is the demo link:
The first demo uses the .style.
method while the second one employs the cssTest
approach;
Furthermore, I also tested both methods in IE8 and found that their execution times were nearly identical.
Does this mean the book's advice is incorrect? Are there other factors at play?