<div>
<div id='test'>Hello</div>
</div>
var el = document.getElementById('test');
const h = el.offsetHeight;
const t = el.offsetTop;
const r = el.getBoundingClientRect();
const h = r.height;
const t = r.top;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
offsetHeight | |
getClientBoundingRect |
Test name | Executions per second |
---|---|
offsetHeight | 1105398.4 Ops/sec |
getClientBoundingRect | 2211329.5 Ops/sec |
Let's break down the provided benchmark definition and test cases.
Benchmark Definition: The benchmark definition is a set of instructions that defines how to measure certain aspects of JavaScript execution performance. In this case, there are two benchmarks:
offsetHeight
: Measures the time it takes to access the offsetHeight
property of an element.getClientBoundingRect
: Measures the time it takes to calculate the client bounding rectangle (i.e., the area of the visible content) of an element.Script Preparation Code:
The script preparation code sets up a variable el
that references an HTML element with the ID "test".
var el = document.getElementById('test');
Html Preparation Code: The html preparation code generates the HTML structure for the benchmark, including an element with the ID "test" containing the text "Hello".
<div>
<div id='test'>Hello</div>
</div>
Now, let's examine each test case:
Test Name: offsetHeight
The test definition is:
const h = el.offsetHeight;
const t = el.offsetTop;
This code accesses the offsetHeight
and offsetTop
properties of the element referenced by el
.
Pros:
Cons:
Test Name: getClientBoundingRect
The test definition is:
const r = el.getBoundingClientRect();
const h = r.height;
const t = r.top;
This code uses the getBoundingClientRect()
method to calculate the client bounding rectangle of the element referenced by el
, and then extracts the height and top properties from the resulting object.
Pros:
Cons:
getBoundingClientRect()
), which may not be supported by all browsers or engines.Now, let's look at the latest benchmark results:
The results show that Chrome 129 running on a Mac OS X 10.15.7 desktop performs better for the getClientBoundingRect
test (2211329 executions per second) compared to the offsetHeight
test (1105398 executions per second).
Library/Additional Context:
In neither of these tests, is there any library or additional context being used that would affect the performance characteristics. However, it's worth noting that the use of getBoundingClientRect()
may involve some overhead due to the need to calculate and return a bounding rectangle.
If test users want to explore other alternatives, here are a few options:
el.offsetLeft
and el.offsetTop
).These alternatives would require additional test cases, script preparation code, and html preparation code to implement.