<div id="teste">teste</div>
document.getElementById('teste').clientHeight;
document.getElementById('teste').offsetHeight;
document.getElementById('teste').getBoundingClientRect().height;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
clientHeight | |
offsetHeight | |
getBoundingClientRect |
Test name | Executions per second |
---|---|
clientHeight | 1425147.5 Ops/sec |
offsetHeight | 1445403.5 Ops/sec |
getBoundingClientRect | 933629.6 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares three methods to get the height of an HTML element:
clientHeight
offsetHeight
getBoundingClientRect().height
These methods are commonly used in web development to measure the size of elements, but they have different implementations and potential performance implications.
Options Compared
Here's a brief overview of each method:
clientHeight
: Returns the height of an element relative to its parent element, taking into account any borders or margins.offsetHeight
, as it only requires one DOM lookup.offsetHeight
: Returns the height of an element relative to the viewport, taking into account any borders, margins, and padding.getBoundingClientRect().height
: Returns the height of an element relative to the viewport, using the getBoundingClientRect()
method, which provides more accurate results than offsetHeight
.offsetHeight
, as it uses a single DOM lookup.getBoundingClientRect()
correctly.Library and Special Features
There are no libraries used in this benchmark. However, the benchmark does use a special JavaScript feature:
getBoundingClientRect()
: Introduced in ECMAScript 2017 (ES2017), this method provides more accurate results for measuring element sizes by taking into account the element's position relative to its nearest ancestors.Other Alternatives
If you need alternative methods or options, here are a few examples:
clientHeight
, you could also use getComputedStyle()
to get the computed style of the element.offsetHeight
, you could use scrollHeight
(for elements with vertical scrollbar) or width
and height
(if you know the element is rectangular).getBoundingClientRect()
, you could also use measure()
in a content script for Chrome extensions.Benchmark Results
The benchmark results show the execution per second for each test case on a specific browser, device platform, and operating system. The results are:
offsetHeight
: 2,362,933 executions/secondclientHeight
: 2,128,213 executions/secondgetBoundingClientRect().height
: 1,682,833 executions/secondThese results indicate that getBoundingClientRect()
is the fastest method in this benchmark, followed by clientHeight
, and then offsetHeight
.