<div id="foo"></div>
var i = 5000;
while (i--) {
checkDisplay('foo');
}
function checkDisplay(id) {
return window.getComputedStyle(document.getElementById(id), null).getPropertyValue("height").slice(0, -2);
}
var i = 5000;
while (i--) {
checkDisplay('foo');
}
function checkDisplay(id) {
return document.getElementById(id).getBoundingClientRect().height;
}
var i = 5000;
while (i--) {
checkDisplay('foo');
}
function checkDisplay(id) {
return document.getElementById(id).clientHeight;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
getComputedStyle | |
getBoundingClientRect | |
clientHeight |
Test name | Executions per second |
---|---|
getComputedStyle | 20.5 Ops/sec |
getBoundingClientRect | 59.4 Ops/sec |
clientHeight | 102.9 Ops/sec |
Let's dive into the world of JavaScript benchmarks!
What is being tested?
The provided benchmark measures the performance of three different approaches to retrieve an element's height in JavaScript:
window.getComputedStyle(document.getElementById(id), null).getPropertyValue("height").slice(0, -2")
: This method retrieves the computed style attribute for the height
property and then extracts a substring from it. The .slice(-2)
part is used to remove the trailing unit (e.g., "px").document.getElementById(id).getBoundingClientRect().height
: This method uses the getBoundingClientRect()
method, which returns a rectangular region that represents the element's size and position relative to the viewport.document.getElementById(id).clientHeight
: This method simply returns the client height of the element, which is the element's own height without any padding or border.Options compared
The benchmark compares the performance of these three approaches on a <div>
element with an ID of "foo".
Pros and Cons:
window.getComputedStyle()
:getBoundingClientRect()
:window.getComputedStyle()
, as it returns a pre-calculated rectangle.clientHeight
:Libraries
None are explicitly mentioned in the provided benchmark code. However, if you're using a library like jQuery or a CSS preprocessor like Sass, they might provide additional functions for working with elements and their styles.
Special JS features or syntax
The benchmark uses JavaScript's while
loop and function definitions to create a simple script that runs 5000 times in a row. This is a basic example of JavaScript's execution context and control flow.
Alternatives
If you're looking for alternative approaches, you might consider:
Keep in mind that benchmarking JavaScript performance is complex and depends on various factors, including the specific use case, browser version, and hardware configuration.