<div id="element" style="background:#555;color:#FFF;position:absolute;left:0;top:0;width:400px;height:100px;">
</div>
var elem = document.getElementById('element');
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
elem.style.width = getRandomInt(500) + 'px';
elem.style.height = '50px';
elem.style.top = '40px';
elem.style.left = '90px';
i++;
elem.style['width'] = getRandomInt(500) + 'px';
elem.style['height'] = '50px';
elem.style['top'] = '40px';
elem.style['left'] = '90px';
elem.setAttribute("style","width:" + getRandomInt(500) + "px;height:50px;top:40px;left:90px;");
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
style by property | |
style by name | |
setAttribute |
Test name | Executions per second |
---|---|
style by property | 321774.6 Ops/sec |
style by name | 375698.9 Ops/sec |
setAttribute | 272987.7 Ops/sec |
The provided JSON represents a JavaScript microbenchmarking test case, designed to compare the performance of three different approaches for setting the style attribute of an HTML element.
Options compared:
elem.style.width = ...
): This approach involves accessing the element's style object and assigning new values directly.setAttribute()
method with a string: This approach involves setting the style attribute of the element as a string, rather than using individual property assignments.Pros and cons:
setAttribute()
method with a string:Library/Feature usage:
The test case uses the Math.random()
function from the built-in JavaScript library. This function generates a random number between 0 (inclusive) and the specified maximum value (exclusive).
Special JS features or syntax:
None of the provided code snippets use any special JavaScript features or syntax.
Other alternatives:
elem.style.width = '500px'
): This approach is similar to setting styles directly using properties, but it uses CSS-specific attribute syntax.style
attribute (e.g., elem.setAttribute('style', 'width: 500px; height: 50px; top: 40px; left: 90px;')
): This approach is similar to using the setAttribute()
method with a string, but it uses template strings to format the style attribute.Benchmarking context:
The test case measures the performance of setting styles directly using properties and using the setAttribute()
method with a string. The benchmark is designed to capture the execution time of each approach on different browsers and devices.