<div class="foo"></div>
var i = 3000;
var div = document.getElementsByClassName('foo')[0];
while (i--) {
chekele(div);
}
function chekele(element) {
return window.getComputedStyle(element, null).display.indexOf('none') === -1;
}
var i = 3000;
while (i--) {
chekele('foo');
}
function chekele(element) {
return document.getElementsByClassName(element)[0].className.indexOf('hide') === -1;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
getComputedStyle | |
className |
Test name | Executions per second |
---|---|
getComputedStyle | 191.7 Ops/sec |
className | 803.6 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Overview
MeasureThat.net is testing two different approaches to check if an element has a style attribute set to "none". The test cases are:
getComputedStyle
: Uses the window.getComputedStyle
method to get the computed style of an element.className2
: Uses a custom approach by checking the className
property of the element.Test Case 1: getComputedStyle
In this test case, the script preparation code is:
var i = 3000;
var div = document.getElementsByClassName('foo')[0];
while (i--) {
chekele(div);
}
The chekele
function checks if the element's display style is not "none" using window.getComputedStyle(element, null).display.indexOf('none') === -1
.
Pros and Cons
Test Case 2: className2
In this test case, the script preparation code is:
var i = 3000;
while (i--) {
chekele('foo');
}
function chekele(element) {
return document.getElementsByClassName(element)[0].className.indexOf('hide') === -1;
}
This approach uses a custom function chekele
to check if the element's class name includes "hide". This is done by getting the first child element with the given class name using document.getElementsByClassName(element)
.
Pros and Cons
Library and Special JS Feature
In both test cases, a library (not explicitly mentioned) is used to get elements from the DOM. The document.getElementsByClassName
method is used to retrieve elements with a specific class name.
There's no special JavaScript feature or syntax being tested in this benchmark.
Other Alternatives
If you want to measure performance of getting CSS styles using other approaches, you could consider:
getComputedStyle
with a different element (e.g., the root element) to avoid any overhead.window.getComputedStyle
with the execution time of className2
in reverse order (i.e., checking if an element is not "hide" instead of checking if it's "none"). CSS
APIs like CSSStyle
or Web APIs
.Keep in mind that these alternatives might require additional modifications to the script preparation code and the test cases.