var notIns = document.createElement("div");
var notInsNested = document.createElement("div");
notIns.appendChild(notInsNested);
var ins = document.createElement("div");
var insNested = document.createElement("div");
ins.appendChild(insNested);
var body = document.body;
body.appendChild(ins);
var test = function(element) {
var parentElement = element.parentElement;
if(parentElement === null) {
return false;
} else if(parentElement === body) {
return true;
}
return test(parentElement);
};
body.contains(notIns);
body.contains(notInsNested);
body.contains(ins);
body.contains(insNested);
test(notIns);
test(notInsNested);
test(ins);
test(insNested);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
body.contains(); direct; notIns | |
body.contains(); nested; notIns | |
body.contains(); direct; ins | |
body.contains(); nested; ins | |
own function; direct; notIns | |
own function; nested; notIns | |
own function; direct; ins | |
own function; nested; ins |
Test name | Executions per second |
---|---|
body.contains(); direct; notIns | 2600025.8 Ops/sec |
body.contains(); nested; notIns | 2634836.0 Ops/sec |
body.contains(); direct; ins | 2579353.0 Ops/sec |
body.contains(); nested; ins | 2574464.2 Ops/sec |
own function; direct; notIns | 3618504.0 Ops/sec |
own function; nested; notIns | 1767283.4 Ops/sec |
own function; direct; ins | 2546186.5 Ops/sec |
own function; nested; ins | 1499364.6 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Purpose
The primary goal of this benchmark is to measure how fast JavaScript can perform two types of DOM (Document Object Model) searches:
Methods Compared
Two methods are being compared:
body.contains()
method to check if an element exists directly within the body element.test()
, to recursively traverse the DOM tree until it finds the target element.Pros and Cons of Each Method
Other Considerations
When writing custom benchmarking code like this one, keep in mind:
Alternative Approaches
Other alternatives to test these methods include:
contains()
method or other native DOM API functions like querySelector()
or getElementById()
.Please note that these alternatives might not necessarily change the fundamental approach of comparing direct vs. own function methods but can offer more sophisticated ways to execute and analyze the benchmarking results.