<div id="foo"></div>
var i = 3000;
var el = document.getElementById('foo');
while (i--) {
chekele(el);
}
function chekele(element) {
return window.getComputedStyle(element, null).getPropertyValue("display").indexOf('none') === -1;
}
var i = 3000;
var el = document.getElementById('foo');
while (i--) {
chekele(el);
}
function chekele(element) {
return element.className.indexOf('hide') === -1;
}
var i = 3000;
var el = document.getElementById('foo');
while (i--) {
chekele(el);
}
function chekele(element) {
return element.classList.contains('hide');
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
getComputedStyle | |
className | |
classList.contains |
Test name | Executions per second |
---|---|
getComputedStyle | 472.9 Ops/sec |
className | 19525.6 Ops/sec |
classList.contains | 6104.4 Ops/sec |
Let's dive into the benchmark.
Benchmark Overview
The provided benchmark measures the performance of three different approaches to check if an element has a display
property set to none
:
getComputedStyle(element, null).getPropertyValue("display").indexOf('none') === -1
element.className.indexOf('hide') === -1
element.classList.contains('hide')
Approach 1: getComputedStyle
This approach uses the window.getComputedStyle
function to retrieve the computed style of an element, specifically the display
property value. The indexOf
method is then used to check if 'none'
is present in the value.
Pros:
display
property.Cons:
Approach 2: className
This approach uses the className
property of an element to check if 'hide'
is present. The indexOf
method is used to find the presence of 'hide'
.
Pros:
Cons:
'hide'
in the class list, not the exact value of the display
property..class1.hide
).Approach 3: classList.contains
This approach uses the classList.contains()
method to check if 'hide'
is present in the class list of an element.
Pros:
className
because it's designed specifically for checking class presence.Cons:
classList
property, which may not be supported in older browsers or in certain environments (e.g., Internet Explorer).Library Used
None of these approaches require any additional libraries beyond standard JavaScript functions. However, if you're using a library like jQuery, you might need to consider its performance impact on your benchmark.
Special JS Feature/Syntax
None of these approaches rely on any special JavaScript features or syntax that would affect their behavior or performance.
Alternatives
If you want to explore alternative approaches, here are a few options:
document.querySelector
and accessing the style
attribute directly (which might be slower than using getComputedStyle
)window.CSS
(if available in your browser)Keep in mind that these alternatives may not offer significant performance improvements over the original three approaches.