<div id="foo">This is a text</div>
var i = 5000;
while (i--) {
checkDisplay('foo');
}
function checkDisplay(id) {
return window.getComputedStyle(document.getElementById(id), null).getPropertyValue("width");
}
var i = 5000;
while (i--) {
checkDisplay('foo');
}
function checkDisplay(id) {
return document.getElementById(id).getBoundingClientRect().width;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
getComputedStyle | |
getBoundingClientRect |
Test name | Executions per second |
---|---|
getComputedStyle | 43.9 Ops/sec |
getBoundingClientRect | 66.3 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Overview
The benchmark compares two approaches to calculate the width of an HTML element: window.getComputedStyle
and document.getElementById().getBoundingClientRect().width
.
Test Cases
There are two test cases:
checkDisplay('foo')
, where checkDisplay
function calculates the width of the HTML element with id "foo" using window.getComputedStyle
.window.getComputedStyle
, it directly accesses the getBoundingClientRect()
method on the document.getElementById('foo')
.Library and Purpose
In both test cases, the checkDisplay
function is not a built-in JavaScript library or syntax. It's a custom function created to measure the performance difference between these two approaches.
However, document.getElementById
and window.getComputedStyle
are built-in JavaScript APIs that interact with the DOM (Document Object Model).
Special JS Features/Syntax
There isn't any specific special JavaScript feature or syntax used in this benchmark. The code only relies on standard JavaScript functionality.
Pros and Cons of Approaches
Here's a brief summary of each approach:
Other Alternatives
If you want to compare these two approaches in different scenarios, you could also consider using other methods:
getComputedStyle
, you could use the Client-side CSS Object Model (CSSOM) API to access the element's styles.Keep in mind that each approach has its own trade-offs and may not be suitable for all scenarios.