<div id="foo">test</div>
const elem = document.getElementById("foo");
var i = 5000;
while (i--) {
getHeight();
}
function getHeight() {
return parseFloat(getComputedStyle(elem).height);
}
const elem = document.getElementById("foo");
var i = 5000;
while (i--) {
getHeight();
}
function getHeight() {
return elem.getBoundingClientRect().height;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
getComputedStyle | |
getBoundingClientRect |
Test name | Executions per second |
---|---|
getComputedStyle | 166.9 Ops/sec |
getBoundingClientRect | 319.9 Ops/sec |
Let's break down what's being tested in the provided JSON benchmark.
Benchmark Overview
The test measures the performance difference between two methods to get the height of an HTML element:
getComputedStyle(elem).height
elem.getBoundingClientRect().height
Options Compared
Two options are compared:
a. getComputedStyle
method:
* Uses the getComputedStyle()
function to dynamically compute the CSS styles of an element.
* Returns the computed style value for a specific property (in this case, height
).
* Can be slower due to the additional computation and parsing required.
b. getBoundingClientRect
method:
* Uses the getBoundingClientRect()
method to get the size of an element relative to its nearest positioned ancestor.
* Returns the bounding rectangle's properties (x, y, width, height) for the given element.
* Typically faster since it only returns a single value (the height in this case).
Pros and Cons
a. getComputedStyle
method:
Pros:
Cons:
b. getBoundingClientRect
method:
Pros:
Cons:
Library and Special JS Features
In this benchmark, no specific libraries are used beyond the standard JavaScript DOM API. However, it's worth noting that getComputedStyle
relies on the CSSOM (CSS Object Model) specification, which can provide additional features for working with styles.
The use of getBoundingClientRect
is a standard DOM method in modern browsers.
Other Alternatives
If you need to measure the performance difference between these two methods, you could also consider using:
document.documentElement.style.top
and elem.offsetTop
(using absolute positioning)elem.offsetWidth
and elem.offsetHeight
(using width and height properties)Keep in mind that these alternatives may have different pros and cons compared to the getComputedStyle
and getBoundingClientRect
methods.
Benchmark Preparation Code
The provided HTML preparation code is:
<div id="foo">test</div>
This creates a simple HTML element with an ID of "foo", which is used as the test subject in both benchmark cases.