A benchmark of different methods to empty an HTML element

ยท

1 min read


function empty(element) {
    if (element.innerHTML) {
        element.innerHTML = "";
    }
}

function empty1(element) {
    element.innerHTML = "";
}

function empty2(element) {
    while (element.firstChild) {
        element.removeChild(element.firstChild);
    }
}

function empty3(element) {
    var child = element.firstChild;
    while (child) {
        element.removeChild(child);
        child = element.firstChild;
    }
}

function empty4(element) {
    var children = element.childNodes;
    for (var i = 0; i < children.length; i++) {
        element.removeChild(children[i]);
    }
}

function empty5(element) {
    var children = element.getElementsByTagName("*");
    for (var i = 0; i < children.length; i++) {
        element.removeChild(children[i]);
    }
}

function empty6(element) {
    var children = element.children;
    for (var i = 0; i < children.length; i++) {
        element.removeChild(children[i]);
    }
}

function empty7(element) {
    while (element.firstChild) {
        element.removeChild(element.firstChild);
    }
    while (element.lastChild) {
        element.removeChild(element.lastChild);
    }
}

// Benchmark the functions

function benchmark(functionName) {
    var start = performance.now();
    for (var i = 0; i < 1000; i++) {
        var element = document.createElement("div");
        for (var k = 0; k < 1000; k++) {
            var child = document.createElement("div");
            element.appendChild(child);
        }
        functionName(element);
    }
    var end = performance.now();
    return end - start;
}


// console.log(benchmark("jQuery $(element).empty"));
console.log("empty", benchmark(empty));
console.log("empty1", benchmark(empty1));
console.log("empty2", benchmark(empty2));
console.log("empty3", benchmark(empty3));
console.log("empty4", benchmark(empty4));
console.log("empty5", benchmark(empty5));
console.log("empty6", benchmark(empty6));
console.log("empty7", benchmark(empty7));
ย