<div id="container"></div>
var node = document.getElementById('container');
for(var i = 0; i < 1; 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');
while(node.firstChild) node.firstChild.remove()
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
innerHTML | |
removeChild | |
remove |
Test name | Executions per second |
---|---|
innerHTML | 1433983.9 Ops/sec |
removeChild | 3865579.8 Ops/sec |
remove | 3806468.5 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
Benchmark Definition
The provided JSON represents a benchmark definition, which is a set of instructions that describes how to create and run a test case. In this case, we have three test cases:
innerHTML
removeChild
remove
(a custom implementation)Each test case has two parts: Script Preparation Code
and Html Preparation Code
.
Script Preparation Code
This code is executed before running each test case. It sets up a container element with an ID of "container" using JavaScript.
var node = document.getElementById('container');
document.getElementById
method returns a reference to the first element with the specified ID.for (var i = 0; i < 1; i++) node.appendChild(document.createElement('div'));
div
element to the container element.appendChild
method adds a child node to the end of an element.Html Preparation Code
This code is executed before running each test case. It creates a basic HTML structure with a container element:
<div id="container"></div>
The purpose of this code is to provide a minimal HTML environment for the test cases to execute in.
Test Cases
Each test case has a unique Benchmark Definition
that describes how to run the test.
innerHTML
node.innerHTML = '';
.removeChild
while (node.firstChild) node.removeChild(node.firstChild);
.remove
(custom implementation)Library
The only library used in this benchmark is JavaScript's built-in DOM API (document.getElementById
, appendChild
, removeChild
, etc.).
Special JS Feature or Syntax
None of the test cases use any special JavaScript features or syntax, such as async/await, promises, or arrow functions.
Pros and Cons of Different Approaches
Here are some pros and cons of each approach:
innerHTML
:removeChild
:innerHTML
, as it only removes child nodes.remove
(custom implementation):Other Alternatives
Some alternative approaches to removing child elements from an element include:
transform
or opacity
properties to hide the content.However, these alternatives may add additional dependencies or complexity to the benchmark, and may not be suitable for all use cases.