<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);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
getBoundingClientRect | |
getLocalDOMRect |
Test name | Executions per second |
---|---|
getBoundingClientRect | 594546.4 Ops/sec |
getLocalDOMRect | 324191.6 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
The provided JSON represents two benchmark test cases, each designed to measure the performance difference between getBoundingClientRect
and getLocalDOMRect
functions.
Test 1: getBoundingClientRect
This test case measures the performance of getBoundingClientRect
, which returns the size and position of an HTML element relative to its parent element. The function takes into account the CSS transformations applied to the element, such as rotations, translations, and scaling.
The pros of using getBoundingClientRect
are:
However, there are some cons:
display: none
or visibility: hidden
.Test 2: getLocalDOMRect
This test case measures the performance of a custom function called getLocalDOMRect
, which manually calculates the element's size and position by traversing its offset parent chain.
The pros of using getLocalDOMRect
are:
getBoundingClientRect
for certain cases, especially when dealing with simple transformations or shallow elements.However, there are some cons:
Library: requestAnimationFrame
Both test cases use requestAnimationFrame
to schedule the benchmark tests. This API allows developers to request the browser to call a specific function at the next animation frame, providing better performance and responsiveness compared to other scheduling methods.
Special JavaScript feature or syntax: None
There are no special JavaScript features or syntaxes being used in these test cases.
Other alternatives:
If you need alternative benchmarking approaches, here are some options:
getBoundingClientRect
, you can use the CSSOMViewports
API to measure an element's size and position.DOMRect
interface to manually calculate an element's size and position.getBoundingClientRect
and CSS calculations to estimate the transformation effects.Keep in mind that each alternative approach has its pros and cons, and may require additional implementation or tweaking to achieve optimal results.