<div id="teste" style="width: 123px">teste</div>
document.getElementById('teste').clientWidth;
document.getElementById('teste').offsetwidth;
parseFloat(window.getComputedStyle(document.getElementById('teste')).width)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
clientWidth | |
offsetwidth | |
window.getComputedStyle |
Test name | Executions per second |
---|---|
clientWidth | 2434950.5 Ops/sec |
offsetwidth | 11214287.0 Ops/sec |
window.getComputedStyle | 1041926.8 Ops/sec |
Overview
MeasureThat.net is a web-based platform for creating and running JavaScript microbenchmarks. The provided benchmark tests the performance of three methods to retrieve the width of an HTML element: clientWidth
, offsetWidth
, and window.getComputedStyle
. We'll dive into each test case, discuss the pros and cons of different approaches, and explore any notable libraries or features used in the benchmark.
Test Cases
The benchmark consists of three individual test cases:
document.getElementById('teste').clientWidth;
This test case measures the performance of retrieving the client width of an HTML element using the clientWidth
property.
document.getElementById('teste').offsetwidth;
This test case measures the performance of retrieving the offset width of an HTML element using the offsetWidth
property.
parseFloat(window.getComputedStyle(document.getElementById('teste')).width);
This test case measures the performance of retrieving the width of an HTML element using the getComputedStyle
method and parsing its value as a float.
Options Compared
The three test cases compare the following options:
Pros and Cons
Here are some pros and cons for each approach:
clientWidth
, as it requires accessing multiple properties.Library and Features
None of the test cases use any notable libraries or features beyond JavaScript's built-in DOM APIs. However, window.getComputedStyle
relies on the CSSOM (CSS Object Model) API, which is a standard for accessing and manipulating CSS styles in web browsers.
Special JS Feature or Syntax
There are no special JS features or syntax used in this benchmark beyond JavaScript's built-in DOM APIs and CSSOM API.
Other Alternatives
If you're looking for alternatives to these test cases, consider the following:
clientWidth
or offsetWidth
, you could use getBoundingClientRect()
or scrollWidth
.In conclusion, this benchmark provides a useful comparison of three methods to retrieve an HTML element's width: clientWidth
, offsetWidth
, and window.getComputedStyle
. Understanding the pros and cons of each approach can help developers make informed decisions about their own code.