This code causes layout thrashing by reading (offsetWidth) and writing (style.height) layout properties in a loop. Each iteration forces the browser to recalculate layout synchronously, creating a performance bottleneck. To optimize: 1) First read all dimensions into an array, 2) Then perform all updates, allowing the browser to batch layout operations. Improved version:
function updateLayout() {
const elements = document.getElementsByClassName('dynamic');
const widths = [];
// Read phase
for (let i = 0; i < elements.length; i++) {
widths[i] = elements[i].offsetWidth;
}
// Write phase
for (let i = 0; i < elements.length; i++) {
elements[i].style.height = widths[i] + 'px';
}
}