<div id="foo"></div>
var i = 3000;
while (i--) {
chekele('foo');
}
function chekele(element) {
return window.getComputedStyle(document.getElementById(element), null).getPropertyValue("display").indexOf('none') === -1;
}
var i = 3000;
while (i--) {
chekele('foo');
}
function chekele(element) {
return document.getElementById(element).className.indexOf('hide') === -1;
}
var i = 3000;
while (i--) {
chekele('foo');
}
function chekele(element) {
return document.getElementById(element).classList.contains('hide');
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
getComputedStyle | |
className | |
classList.contains |
Test name | Executions per second |
---|---|
getComputedStyle | 201.3 Ops/sec |
className | 924.6 Ops/sec |
classList.contains | 800.2 Ops/sec |
I'll dive into explaining the benchmark.
What is being tested?
MeasureThat.net is testing three different approaches to check if an HTML element has a display
property set to none
. The elements are checked using:
window.getComputedStyle(document.getElementById(element), null).getPropertyValue("display").indexOf('none') === -1
: This approach uses the getComputedStyle()
method to get the computed style of the element, specifically the value of the display
property. It then checks if the indexOf('none')
returns -1
, which means the display
property is not set to none
.document.getElementById(element).className.indexOf('hide') === -1
: This approach uses the className
property of the element to check if it contains the string 'hide'
. The idea is that if the element has a class named hide
, its display
property should be set to none
.document.getElementById(element).classList.contains('hide')
: This approach uses the classList
property (introduced in HTML5) to check if the element contains the string 'hide'
. Similar to the previous approach, it assumes that having a class named hide
means its display
property is set to none
.Options compared
The three approaches are being compared to determine which one is the most efficient.
Pros and cons of each approach:
window.getComputedStyle()
:className
:display
property is set using CSS styles that are not included in the element's class list).classList.contains()
:className
approach.Library used
None of these approaches use any specific libraries, but they do rely on built-in JavaScript features like window.getComputedStyle()
, document.getElementById()
, and classList
.
Special JS feature/syntax
No special JavaScript features or syntax are used in this benchmark. It only relies on standard JavaScript features.
Other alternatives
There may be other approaches to check if an element has a display
property set to none
. Some possible alternatives include:
:empty
or ::before
pseudo-classes) to detect the presence of a class named hide
.style
property directly instead of relying on window.getComputedStyle()
.However, these alternatives are not being tested in this benchmark.