<div id="test">test</div>
var test_n = '123px';
var _style = window.getComputedStyle(document.getElementById('test'));
document.getElementById('test').offsetWidth;
document.getElementById('test').getBoundingClientRect().width;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
offsetWidth | |
getBoundingClientRect |
Test name | Executions per second |
---|---|
offsetWidth | 1453534.2 Ops/sec |
getBoundingClientRect | 958369.4 Ops/sec |
In the provided benchmark, we are comparing the performance of two different methods for obtaining the width of a DOM element in JavaScript: offsetWidth
and getBoundingClientRect
.
offsetWidth
document.getElementById('test').offsetWidth;
getBoundingClientRect
document.getElementById('test').getBoundingClientRect().width;
DOMRect
object providing the size of the element and its position relative to the viewport. The width property of the DOMRect
is what we are measuring here.Pros:
offsetWidth
is straightforward to use and understand.Cons:
offsetWidth
offers only the width, without information about the position relative to the viewport or any transformation effects.Pros:
Cons:
offsetWidth
since it computes the rectangle including layout adjustments.offsetWidth
when you need only the width and performance is critical, while getBoundingClientRect
should be used when you need both size and position on the screen.Other methods to measure widths include:
offsetWidth
, but excludes borders and scrollbars. It is helpful if you need the inner width for a box-model calculation.The benchmark provides a clear comparison of two common methods for measuring element width in JavaScript. This knowledge is crucial for developers focused on optimizing performance in web applications while considering accuracy and the specific context of measurement needs.