<div id="foo"></div>
var i = 5000;
while (i--) {
checkDisplay('foo');
}
function checkDisplay(id) {
return window.getComputedStyle(document.getElementById(id), null).getPropertyValue("height");
}
var i = 5000;
while (i--) {
checkDisplay('foo');
}
function checkDisplay(id) {
return document.getElementById(id).getBoundingClientRect().height;
}
var i = 5000;
while (i--) {
checkDisplay('foo');
}
function checkDisplay(id) {
return document.getElementById(id).clientHeight;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
getComputedStyle | |
getBoundingClientRect | |
clientHeight |
Test name | Executions per second |
---|---|
getComputedStyle | 150.1 Ops/sec |
getBoundingClientRect | 205.3 Ops/sec |
clientHeight | 290.3 Ops/sec |
Let's break down the benchmark and explain what is being tested.
Benchmark Description
The benchmark measures the performance of three different approaches to retrieve the height of an HTML element:
getComputedStyle
: Uses the getComputedStyle
method to get the computed style attribute of the element.getBoundingClientRect
: Uses the getBoundingClientRect
method to get the size of the bounding rectangle of the element.clientHeight
: Uses the clientHeight
property to get the height of the element's content area.Approaches Comparison
The three approaches are compared in terms of their performance, which is measured by the number of executions per second.
height
, which may require additional processing.getComputedStyle
since it doesn't involve a CSSOM API call and returns only the height property.getBoundingClientRect
but potentially faster than getComputedStyle
since it:Library and Special JS Feature
There are no libraries used in this benchmark. However, note that getComputedStyle
uses a proprietary API (CSSOM) that is not part of the standard JavaScript API.
Considerations
When choosing an approach, consider the following factors:
getComputedStyle
might be a better choice.getBoundingClientRect
or clientHeight
might be a better option.clientHeight
requires less code than getComputedStyle
or getBoundingClientRect
.Alternatives
Other approaches to retrieve an element's height include:
offsetHeight
property (not shown in this benchmark).Keep in mind that these alternatives might have different performance characteristics compared to the methods tested in this benchmark.