remove all content from an element (v586)

Revision 586 of this benchmark created on


Description

Which method to remove all content from an element is fastest?

jsperf setup does not run before each test, but before each test loop. We reset() the element after each iteration to (a) throw an exception if it isn't empty, and (b) add the same child elements back to it for the next iteration.

Preparation HTML

<div id="box" style="display:none;"></div>
<script>
var box = document.getElementById('box');
var fragment = document.createDocumentFragment();
for (var i = 0; i < 500; i++) {
	var c = document.createElement('div');
	c.textContent = 'asdf' + Date.now();
	fragment.appendChild(c);
}
function reset(ignore) {
	if (!ignore && box.childNodes.length > 0) throw 'child nodes not cleared!';
	box.appendChild(fragment.cloneNode(true));
}
var slice = Array.prototype.slice;
</script>

Setup

reset(true);

Test runner

Ready to run.

Testing in
TestOps/sec
while firstChild removeChild firstChild
while (box.firstChild) {
	box.removeChild(box.firstChild);
}
reset();
ready
while firstChild removeChild lastChild
while (box.firstChild) {
	box.removeChild(box.lastChild);
}
reset();
ready
while lastChild removeChild firstChild
while (box.lastChild) {
	box.removeChild(box.firstChild);
}
reset();
ready
while lastChild removeChild lastChild
while (box.lastChild) {
	box.removeChild(box.lastChild);
}
reset();
ready
while var firstChild removeChild var
var child;
while (child = box.firstChild) {
	box.removeChild(child);
}
reset();
ready
while var lastChild removeChild var
var child;
while (child = box.lastChild) {
	box.removeChild(child);
}
reset();
ready
while not-null firstChild removeChild firstChild
while (box.firstChild !== null) {
	box.removeChild(box.firstChild);
}
reset();
ready
while not-null firstChild removeChild lastChild
while (box.firstChild !== null) {
	box.removeChild(box.lastChild);
}
reset();
ready
while not-null lastChild removeChild firstChild
while (box.lastChild !== null) {
	box.removeChild(box.firstChild);
}
reset();
ready
while not-null lastChild removeChild lastChild
while (box.lastChild !== null) {
	box.removeChild(box.lastChild);
}
reset();
ready
while hasChildNodes removeChild firstChild
while (box.hasChildNodes()) {
	box.removeChild(box.firstChild);
}
reset();
ready
while hasChildNodes removeChild lastChild
while (box.hasChildNodes()) {
	box.removeChild(box.lastChild);
}
reset();
ready

Revisions

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