<div id="el" style="transform: rotateZ(45deg)">
<h2>Lorem ipsum dolor sit amet</h2>
</div>
function getLocalDOMRect(el) {
let offsetTop = 0;
let offsetLeft = 0;
const width = el.offsetWidth;
const height = el.offsetHeight;
while (el instanceof HTMLElement) {
offsetTop += el.offsetTop;
offsetLeft += el.offsetLeft;
el = el.offsetParent;
}
return new DOMRect(offsetLeft, offsetTop, width, height);
}
const el = document.getElementById("el");
const { left, right, top, bottom } = el.getBoundingClientRect();
const { left, right, top, bottom } = getLocalDOMRect(el);
const { offsetWidth, offsetHeight, offsetTop } = el;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
getBoundingClientRect | |
getLocalDOMRect | |
Access offset properties directly |
Test name | Executions per second |
---|---|
getBoundingClientRect | 652922.8 Ops/sec |
getLocalDOMRect | 80458.5 Ops/sec |
Access offset properties directly | 240281.2 Ops/sec |
I'll break down the provided benchmark and its test cases.
Benchmark Definition JSON
The getBoundingClientRect vs offset
benchmark compares three approaches to retrieve the dimensions of an HTML element:
Comparison Options
The benchmark tests the following options:
getBoundingClientRect
vs getLocalDOMRect
: Measures which approach is faster for retrieving an element's dimensions.Access offset properties directly
: Tests how fast it is to access the offset properties (offsetWidth
, offsetHeight
, and offsetTop
) of an element.Pros and Cons
Here are some pros and cons of each approach:
Library Usage
None of the test cases use a JavaScript library explicitly. However, getBoundingClientRect
is a standard method provided by modern browsers' API.
Special JS Feature or Syntax
There's no special JavaScript feature or syntax being tested here. The focus is on comparing the performance of different approaches to retrieve an element's dimensions.
Other Alternatives
For benchmarking purposes, you might also consider:
getComputedStyle
to access CSS stylesrequestAnimationFrame
for updates vs. polling at regular intervalsIn summary, this benchmark helps evaluate the relative performance of three approaches for retrieving an element's dimensions: getBoundingClientRect
, a custom getLocalDOMRect
function, and direct access to offset properties.