<div id="teste">teste</div>
var teste_n = '123px';
var _style = window.getComputedStyle(document.getElementById('teste'));
document.getElementById('teste').clientWidth;
document.getElementById('teste').offsetwidth;
document.getElementById('teste').scrollWidth;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
clientWidth | |
offsetWidth | |
scrollWidth |
Test name | Executions per second |
---|---|
clientWidth | 607311.1 Ops/sec |
offsetWidth | 4446076.5 Ops/sec |
scrollWidth | 600328.1 Ops/sec |
Benchmark Overview
The provided JSON represents a JavaScript microbenchmark created on MeasureThat.net. The benchmark compares the performance of three different methods to retrieve the width of an HTML element: clientWidth
, offsetWidth
, and scrollWidth
.
Test Case 1: clientWidth
offsetWidth
, scrollWidth
) for a direct comparison.offsetWidth
or scrollWidth
since it only needs to calculate the width relative to its parent element.Test Case 2: offsetWidth
window.getComputedStyle
is used to access the computed style of the element.clientWidth
since it needs to access and calculate more information.Test Case 3: scrollWidth
Element.scrollWidth
).offsetWidth
due to additional calculations.Special Considerations
The benchmark does not use any special JavaScript features or syntax that would require specific attention. However, it is worth noting that the use of window.getComputedStyle
can introduce additional overhead compared to accessing an element's style directly.
Other Alternatives
Some alternative methods to compare with these three might include:
getBoundingClientRect().width
document.getElementById('teste').cssWidth
)CanvasRenderingContext2D.measureText()
)Keep in mind that these alternatives may not be as straightforward to implement and might introduce additional overhead or complexities.
Benchmark Preparation Code Explanation
The script preparation code snippet sets up a test environment by:
_teste_n
with the value '123px'
.document.getElementById('teste')
) using window.getComputedStyle
.This setup allows the benchmark to test the performance of retrieving the width of an element in different contexts.
Latest Benchmark Result Explanation
The latest benchmark result provides a summary of the execution times for each test case:
offsetWidth
: 607.311 secondsclientWidth
: 444.607 secondsscrollWidth
: 600.328 secondsThese results indicate that, on this specific setup and device, clientWidth
is the fastest method to retrieve an element's width, followed by scrollWidth
, and then offsetWidth
.