I reviewed all questions and decided to test performance for most crucial test case:
- we need to clear content
- we need to keep original element
- we need to delete a lot of child elements
So my HTML:
<div id="target">
<div><p>Title</p></div>
<!-- 1000 at all -->
<div><p>Title</p></div>
</div>
// innerHTML
target.innerHTML = "";
// lastChild
while (target.hasChildNodes()) {
target.removeChild(target.lastChild);
}
// firstChild
while (target.hasChildNodes()) {
target.removeChild(target.firstChild);
}
// replaceChildren
target.replaceChildren();
Results:
Checked test: innerHTML x 1,222,273 ops/sec ±0.47% (63 runs sampled)
Checked test: lastChild x 1,336,734 ops/sec ±0.87% (65 runs sampled)
Checked test: firstChild x 1,313,521 ops/sec ±0.74% (64 runs sampled)
Checked test: replaceChildren x 743,076 ops/sec ±1.08% (53 runs sampled)
Checked test: innerHTML x 1,202,727 ops/sec ±0.83% (63 runs sampled)
Checked test: lastChild x 1,360,350 ops/sec ±0.72% (65 runs sampled)
Checked test: firstChild x 1,348,498 ops/sec ±0.78% (63 runs sampled)
Checked test: replaceChildren x 743,076 ops/sec ±0.86% (53 runs sampled)
Checked test: innerHTML x 1,191,838 ops/sec ±0.73% (62 runs sampled)
Checked test: lastChild x 1,352,657 ops/sec ±1.42% (63 runs sampled)
Checked test: firstChild x 1,327,664 ops/sec ±1.27% (65 runs sampled)
Checked test: replaceChildren x 754,166 ops/sec ±1.88% (61 runs sampled)
Conclusions
Modern API is most slow. First child and last child ways are equal, some side effect can be present if comparison happens with multiple cases. But side by side you can see here:
Checked test: firstChild x 1,423,497 ops/sec ±0.53% (63 runs sampled)
Checked test: lastChild x 1,422,560 ops/sec ±0.36% (66 runs sampled)
Checked test: firstChild x 1,368,175 ops/sec ±0.57% (65 runs sampled)
Checked test: lastChild x 1,381,759 ops/sec ±0.39% (66 runs sampled)
Checked test: firstChild x 1,372,109 ops/sec ±0.37% (66 runs sampled)
Checked test: lastChild x 1,355,811 ops/sec ±0.35% (65 runs sampled)
Checked test: lastChild x 1,364,830 ops/sec ±0.65% (64 runs sampled)
Checked test: firstChild x 1,365,617 ops/sec ±0.41% (65 runs sampled)
Checked test: lastChild x 1,389,458 ops/sec ±0.50% (63 runs sampled)
Checked test: firstChild x 1,387,861 ops/sec ±0.40% (64 runs sampled)
Checked test: lastChild x 1,388,208 ops/sec ±0.43% (65 runs sampled)
Checked test: firstChild x 1,413,741 ops/sec ±0.47% (65 runs sampled)
P.S. Browser: Firefox 111.0.1