<div id="testdiv">
<div class="unique">test</div>
</div>
var i, imax;
var div = document.getElementById('testdiv');
var newDiv = document.createElement('div');
newDiv.classList.add('unique');
newDiv.innerText = 'test';
div.innerHTML = newDiv;
var newDiv = `<div class="unique">test</div>`;
div.insertAdjacentHTML("beforeend",newDiv)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
createElement | |
template string |
Test name | Executions per second |
---|---|
createElement | 19214.2 Ops/sec |
template string | 51642.8 Ops/sec |
Let's break down the provided benchmark and explain what is being tested, compared, and other considerations.
Benchmark Definition
The benchmark is designed to compare two approaches for inserting HTML content into an existing HTML element:
createElement
method: Creating a new div
element using document.createElement()
and then modifying its properties (class name and text content).insertAdjacentHTML()
: Using a string template (<div class="unique">test</div>
) and inserting it into the div
element using insertAdjacentHTML()
.Options Compared
The two options are being compared in terms of:
Pros and Cons of Each Approach
insertAdjacentHTML()
Pros:
Cons:
Library and Special JS Feature
The insertAdjacentHTML()
method is a part of the DOM API, which is built-in to most modern browsers. No external library or special JavaScript feature is required.
However, if you're using an older browser that doesn't support insertAdjacentHTML()
, you can use alternative methods like innerHTML
or appendChild()
with some creative manipulation.
Other Considerations
When evaluating this benchmark, keep in mind:
createElement
method might be more suitable for scenarios where flexibility is crucial (e.g., dynamic DOM manipulation).insertAdjacentHTML()
might be preferred for scenarios where conciseness and efficiency are important.Alternatives
If you're looking for alternatives or variations, consider:
appendChild()
, innerHTML
).In summary, this benchmark provides a straightforward comparison between two approaches for inserting HTML content into an existing element, highlighting the trade-offs between flexibility, performance, and memory usage.