Fastest method of clearing all children from a DOM element

JavaScript performance comparison

Revision 475 of this test case created by

Preparation code

<div id="container"></div>
      
<script>
Benchmark.prototype.setup = function() {
  document.getElementById('container').innerHTML = '<div id="box"><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span></div>';
  var box = document.getElementById('box');

};
</script>

Preparation code output

<div id="container"></div>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
innerText = ''
box.innerText = '';
pending…
removeChild(box.firstChild)
while (box.firstChild) {
  box.removeChild(box.firstChild);
}
pending…
textContent = '';
box.textContent = '';
pending…
removeChild(box.lastChild)
while (box.childNodes.length > 1) {
  box.removeChild(box.childNodes[box.childNodes.length - 2]);
}
box.removeChild(box.lastChild);
pending…
cachedLastChild
let child;
while (child = box.lastChild) {
  box.removeChild(child);
}
pending…
Never do it like this
let i,
		parent,
		children = box.childNodes,
		count = children.length;

	for (i = count - 1; i >= 0; i--) {
		parent = children[i].parentNode;

		if (parent) {
			parent.removeChild(children[i]);
		}
	}
pending…
innerHTML = ''
box.innerHTML = '';
pending…
removeChild(box.lastChild)
while (box.lastChild) {
  box.removeChild(box.lastChild);
}
pending…
cloneNode(false)
box.replaceWith(box.cloneNode(false));
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL.

0 Comments