<div id="foo"></div>
var i = 5000;
while (i--) {
checkDisplay('foo');
}
function checkDisplay(id) {
return window.getComputedStyle(document.getElementById(id), null).getPropertyValue("display") === "none";
}
var i = 5000;
while (i--) {
checkDisplay('foo');
}
function checkDisplay(id) {
return document.getElementById(id).getBoundingClientRect().width === 0;
}
var i = 5000;
while (i--) {
checkDisplay('foo');
}
function checkDisplay(id) {
return window.getComputedStyle(document.getElementById(id), null);
}
var i = 5000;
while (i--) {
checkDisplay('foo');
}
function checkDisplay(id) {
return document.getElementById(id);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
getComputedStyle | |
getBoundingClientRect | |
getComputedStyle without getters | |
getElementById |
Test name | Executions per second |
---|---|
getComputedStyle | 331.5 Ops/sec |
getBoundingClientRect | 231.4 Ops/sec |
getComputedStyle without getters | 586.3 Ops/sec |
getElementById | 2136.9 Ops/sec |
Overview of the Benchmark
The provided benchmark measures the performance of three different approaches for checking if an element's display property is set to "none":
window.getComputedStyle(document.getElementById(id), null).getPropertyValue("display") === "none"
document.getElementById(id).getBoundingClientRect().width === 0
window.getComputedStyle(document.getElementById(id))
Options Compared
The benchmark compares the performance of these three approaches:
window.getComputedStyle
with and without getters (property accessors) for getting the computed style values.document.getElementById
followed by checking the element's bounding rectangle width.Pros and Cons of Each Approach:
window.getComputedStyle
with getters:display
, using the property accessor syntax (window.getComputedStyle(document.getElementById(id), null).getPropertyValue("display")
).window.getComputedStyle
without getters:document.getElementById
followed by getBoundingClientRect().width === 0
:Library Used:
None. This benchmark only uses built-in JavaScript functions and DOM API methods.
Special JS Feature/Syntax:
None mentioned in the provided code.
Other Considerations:
When deciding which approach to use, consider the trade-offs between precision, performance, and simplicity:
window.getComputedStyle
with getters might be the best choice.window.getComputedStyle
without getters or relying on getBoundingClientRect()
might be more suitable.Alternatives:
Other approaches for checking if an element's display property is set to "none" could include:
cssom
) for more efficient styling and layout management.Keep in mind that each approach has its strengths and weaknesses, and the chosen method will depend on the specific requirements of your use case.