<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;
}
const ui = 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;
}
const ui = new UI(document);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
appendChild | |
insertAdjacentHTML |
Test name | Executions per second |
---|---|
appendChild | 7275.7 Ops/sec |
insertAdjacentHTML | 3245.2 Ops/sec |
Measuring the performance of JavaScript microbenchmarks, such as those found on MeasureThat.net, involves analyzing and comparing different approaches to accomplish a specific task.
The benchmark provided measures the performance difference between using appendChild
and insertAdjacentHTML
methods when creating a dialog box with an image in it. Here's what each option is about:
Option 1: Appending elements to the document body
In this approach, you create a new element (in this case, a dialog box) and append it to the end of the document body using appendChild
. This method can lead to performance issues if not used carefully, as it involves creating a new DOM tree node every time.
Pros:
Cons:
Option 2: Using insertAdjacentHTML
In this approach, you use the insertAdjacentHTML
method to insert an HTML string directly into the document. This method is more efficient than appending individual elements because it reduces the number of DOM mutations.
Pros:
Cons:
insertAdjacentHTML
(e.g., HTML elements)Other considerations:
DocumentFragment
class is used in both test cases to create a placeholder for the dialog box. This allows the appendChild
method to work correctly, as it doesn't have to create a new DOM tree node from scratch.let
, const
, and template literals are used throughout the benchmark to define variables and expressions.To use these approaches, you would typically:
appendChild
or insertAdjacentHTML
method to create the dialog box.Alternatives to these approaches include: