<div id="el" style="transform: rotateZ(45deg)">
<h2>Lorem ipsum dolor sit amet</h2>
</div>
const el = document.getElementById("el");
const width = el.getBoundingClientRect().width;
const width = el.offsetWidth;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
getBoundingClientRect | |
Access offset properties directly |
Test name | Executions per second |
---|---|
getBoundingClientRect | 1771613.1 Ops/sec |
Access offset properties directly | 3379068.5 Ops/sec |
The benchmark focuses on comparing the performance of two different methods for obtaining the width of a DOM element in a web page, specifically looking at the width of an element that has been transformed with CSS. The two methods being tested are:
getBoundingClientRect().width
offsetWidth
, particularly on resource-constrained devices or when called frequently due to reflow implications in the rendering engine.offsetWidth
getBoundingClientRect()
does.getBoundingClientRect()
since it directly accesses the layout properties without recalculating the rendering state.Use Cases:
getBoundingClientRect()
when you need the actual size of an element as it appears on the screen, especially if transformations are involved.offsetWidth
for simpler cases where performance is a concern and transformations are not an issue, or when the speed of accessing the width is more critical than its accuracy.Browser Compatibility:
This benchmark doesn't utilize any external libraries, but it relies on standard DOM API methods provided by browsers. The methods are intrinsic to the JavaScript environment, and thus not reliant on any user-defined functionalities.
ClientRect:
getComputedStyle
to fetch styles directly and manually calculate dimensions. This approach, however, can be significantly more complex and is usually not recommended for simple width retrieval.CSS/JavaScript Frameworks:
In conclusion, this benchmark effectively pits getBoundingClientRect().width
against offsetWidth
, highlighting their respective use cases and performance differences within a real-world application context. Understanding how these two methods function allows developers to optimize performance based on their specific needs and the conditions in which their web applications operate.