<div id="foo">aaaaa</div>
var i = 5000;
while (i--) {
checkDisplay('foo');
}
function checkDisplay(id) {
return window.getComputedStyle(document.getElementById(id), null).getPropertyValue("width");
}
var i = 5000;
while (i--) {
checkDisplay('foo');
}
function checkDisplay(id) {
return document.getElementById(id).getBoundingClientRect().width;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
getComputedStyle | |
getBoundingClientRect |
Test name | Executions per second |
---|---|
getComputedStyle | 308.1 Ops/sec |
getBoundingClientRect | 470.0 Ops/sec |
The benchmark described in the JSON provided compares two different methods for retrieving the width of a DOM element in a web page. The methods being tested are window.getComputedStyle
and getBoundingClientRect
.
#foo
).getComputedStyle
Method:
var i = 5000;
while (i--) {
checkDisplay('foo');
}
function checkDisplay(id) {
return window.getComputedStyle(document.getElementById(id), null).getPropertyValue("width");
}
getBoundingClientRect
Method:
var i = 5000;
while (i--) {
checkDisplay('foo');
}
function checkDisplay(id) {
return document.getElementById(id).getBoundingClientRect().width;
}
DOMRect
object providing information about the size of an element and its position relative to the viewport. The width
property returns the width of the element, including padding and border, but excluding margins.getBoundingClientRect
: Executions per second: 470.04getComputedStyle
: Executions per second: 308.05From the benchmark results, it is clear that getBoundingClientRect
is the faster option for retrieving the width of the element in this context.
getComputedStyle
:Pros:
Cons:
getBoundingClientRect
.getBoundingClientRect
:Pros:
Cons:
visibility: hidden
.getBoundingClientRect
is generally the more performant and reliable method to use.getComputedStyle
would be more suitable despite its slower performance.In summary, the benchmark highlights the performance differences between direct DOM measurements and computed styles, directing developers towards the most effective means to retrieve an element's width based on the use case.