I found a weird case of forced reflow when we use loop. Example here
In the first case, I have looped through 200 elements and change its class using for loop.
function resize1(){
let children = parent1.children;
clicked2 = !clicked2;
for(let i=0;i<200;i++){
let child = children[i];
let { width } = window.getComputedStyle(child);
isLarge = clicked2 ? i % 2 === 0 : i % 2=== 1;
if(isLarge){
child.classList.add('large');
child.classList.remove('small');
}
else{
child.classList.add('small');
child.classList.remove('large');
}
// size = window.getComputedStyle(child).margin;
}
}Instead of looping I again went through each child elements and changed the same class.
let width, isLarge, i =0, child;
child = parent.children[i];
width = window.getComputedStyle(child);
isLarge = clicked ? i % 2 === 0 : i % 2=== 1;
if(isLarge){
child.classList.add('large');
child.classList.remove('small');
}
else{
child.classList.add('small');
child.classList.remove('large');
}
i++;
child = parent.children[i];
width = window.getComputedStyle(child);
isLarge = clicked ? i % 2 === 0 : i % 2=== 1;
if(isLarge){
child.classList.add('large');
child.classList.remove('small');
}
else{
child.classList.add('small');
child.classList.remove('large');
}
i++;(*200 elements) I know this case is weird but when I checked for performance the second case takes less amount of time in chrome dev tools and reflow also occurs in looping case only.
from Looping causes forced reflow while the same code doesn't cause reflow without loop

No comments:
Post a Comment