<div id="foo" data-attr="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).getAttribute('data-attr');
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
getComputedStyle | |
getAttribute |
Test name | Executions per second |
---|---|
getComputedStyle | 929.0 Ops/sec |
getAttribute | 3606.1 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark is comparing two approaches to check if an element with a specific attribute exists: window.getComputedStyle
and getAttribute
. The test case uses a simple HTML page with a single <div>
element having a data-attr
attribute set to "foo".
Options Compared
There are two options being compared:
window.getComputedStyle
: This method retrieves the computed style of an element, including its display property. In this case, it checks if the display
property is not equal to 'none'
, which would indicate that the element exists.getAttribute
: This method returns the value of a specific attribute on an element. In this case, it retrieves the value of the data-attr
attribute.Pros and Cons
window.getComputedStyle
:getAttribute
:Library Usage
There is no explicit library usage in this benchmark. However, window.getComputedStyle
relies on the Web API to access the DOM tree and retrieve computed styles.
Special JS Features/Syntax
None of the provided test cases use any special JavaScript features or syntax. They are straightforward and focus on comparing two basic approaches.
Alternatives
Other alternatives for checking element existence could include:
element.matches()
with a CSS selectorKeep in mind that the choice of approach depends on the specific use case and performance requirements.