<div id="container"></div>
var node = document.getElementById('container');
for(var i = 0; i < 1000; i++) node.appendChild(document.createElement('div'));
var node = document.getElementById('container');
node.innerHTML = '';
var node = document.getElementById('container');
while(node.firstChild) node.removeChild(node.firstChild)
var node = document.getElementById('container');
var r = document.createRange();
r.selectNodeContents(node);
r.deleteContents();
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
innerHTML | |
removeChild | |
create range |
Test name | Executions per second |
---|---|
innerHTML | 273823.8 Ops/sec |
removeChild | 2177931.0 Ops/sec |
create range | 575988.0 Ops/sec |
Let's break down the provided JSON and explain what's being tested, the different approaches compared, their pros and cons, and other considerations.
Benchmark Definition
The benchmark defines two scripts that are to be executed:
innerHTML
: This script sets the inner HTML of an element (var node = document.getElementById('container');\nnode.innerHTML = '';
).removeChild
: This script removes all child nodes from an element (var node = document.getElementById('container');\nwhile(node.firstChild) node.removeChild(node.firstChild)
).create range
: This script creates a Range object, selects its contents, and then deletes them (var node = document.getElementById('container');\nvar r = document.createRange();\nr.selectNodeContents(node);\nr.deleteContents()
).Options Compared
The benchmark compares the execution time of these three scripts on different nodes:
innerHTML
: Sets the inner HTML of an element.removeChild
: Removes all child nodes from an element.create range
: Creates a Range object, selects its contents, and then deletes them.Pros and Cons
innerHTML
because it only removes one node at a time, which can reduce memory usage and garbage collection. However, it's slower for large numbers of child nodes.removeChild
due to the creation of a Range object.Library Usage
The benchmark uses the following libraries:
Special JS Features or Syntax
None mentioned
Other Considerations
The benchmark also considers the device platform, operating system, and browser version, which can affect execution time. The ExecutionsPerSecond
value represents the number of executions per second.
Alternatives
If you were to rewrite this benchmark, you might consider adding additional test cases, such as:
div
, span
, p
)addEventListener
, innerHTML +=
, etc.)Additionally, you could consider using a benchmarking library like WebPageTest or Benchmark.js to create and run benchmarks.