<div><div><div></div></div></div>
<div></div>
<a href='#' />
<div></div>
<div></div>
<div><div><div></div></div></div>
<div></div>
<div><div></div></div>
<div><div></div></div>
<div><div><div><div></div></div></div></div>
<div></div>
<div></div>
for(let i of [Document,DocumentFragment,Element]){
i.prototype.$=i.prototype.querySelector;
i.prototype.$$=function(s){return[this.querySelectorAll(s)]};
}
class UI {
constructor(doc){
this.#dlg = document.createElement('dialog');
this.#dlg.id = 'dlg';
this.#dlg.className = 'fit';
this.#img = this.#dlg.appendChild(new Image());
document.body.appendChild(this.#dlg);
}
#dlg;
#img;
}
for (i = 0; i < 1000; i++) new UI(document);
class UI {
constructor(doc){
doc.body.insertAdjacentHTML('beforeend',`<dialog id="dlg" class="fit"><img></dialog>`);
this.#dlg = doc.body.$('#dlg');
this.#img = this.#dlg.$('img');
}
#dlg;
#img;
}
for (i = 0; i < 1000; i++) new UI(document);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
appendChild | |
insertAdjacentHTML |
Test name | Executions per second |
---|---|
appendChild | 3.8 Ops/sec |
insertAdjacentHTML | 1.6 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net!
What is tested?
The provided benchmark tests two approaches to appending or inserting HTML content into a document:
appendChild
: This method adds the specified element as a child of another element, in this case, a div
element.insertAdjacentHTML
: This method inserts a string representing an HTML fragment (in this case, a dialog element with an image) at a specific position relative to the target element.Options compared
The benchmark compares the performance of these two approaches on various elements:
Document
objectDocumentFragment
objectElement
objectsPros and Cons
Here's a brief summary of each approach:
insertAdjacentHTML
for large amounts of content.appendChild
for large amounts of content.Library and purpose
The benchmark uses the Element.prototype.$=
property, which is not a standard property. However, it's possible that this property is defined in a custom library or framework being tested.
Unfortunately, without more information about the specific library or context, I couldn't provide further details.
Special JavaScript features or syntax
There are no special JavaScript features or syntax mentioned in the benchmark definition or test cases.
Other alternatives
If you're interested in exploring alternative approaches to appending or inserting content into a document, here are some options:
insertBefore()
: Similar to appendChild
, but inserts the specified element before another element.createElement()
: Creates a new HTML element using the DOM API.innerHTML
property: Sets or gets the inner HTML of an element.Keep in mind that each approach has its own trade-offs and considerations, and the choice ultimately depends on your specific use case and requirements.