<div id="viewer"></div>
const lines = 50000;
let data = '';
for(let i = 0; i<=lines; i++) {
data += `<div class="row"><span id="line-${i}">${i}</span><span>Foo Bar ${i}</span></div>`
}
const el = document.getElementById('viewer');
el.innerHTML = data;
const lines = 50000;
let data = '';
for(let i = 0; i<=lines; i++) {
data += `<div class="row"><span id="line-${lines[i]}">${lines[i]}</span><span>Foo Bar ${lines[i]}</span></div>`
}
const fragment = document.createDocumentFragment();
const wrapper = document.createElement('div');
const el = document.getElementById('viewer');
wrapper.innerHTML = data.html;
fragment.appendChild(wrapper);
el.appendChild(fragment);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
innerHTML | |
DocumentFragment |
Test name | Executions per second |
---|---|
innerHTML | 3.3 Ops/sec |
DocumentFragment | 33.4 Ops/sec |
Benchmark Overview
MeasureThat.net is a website that allows users to create and run JavaScript microbenchmarks. The provided JSON represents two benchmark cases, each comparing the performance of two different approaches: innerHTML
and DocumentFragment
.
Tested Options
The two test cases compare the performance of:
innerHTML
property. It is a simple and widely used method for updating the content of an HTML document.wrapper
). This approach can be more efficient than innerHTML
because it avoids the overhead of parsing the HTML content multiple times.Pros and Cons
innerHTML
for large or complex HTML content, reduces parsing overhead.Library and Its Purpose
In both test cases, the DocumentFragment
library is used. A DocumentFragment
is a lightweight object that allows you to create a clone of an HTML document or a part of one, without actually creating new DOM elements. It's useful for optimizing performance when dealing with large amounts of HTML content.
Special JavaScript Features or Syntax
None are mentioned in the provided JSON. However, it's worth noting that DocumentFragment
is a built-in feature in modern browsers, and its usage is well-documented.
Other Alternatives
If you're looking for alternative approaches to compare performance, here are some options:
createElement
and appends them to another element using appendChild
. While not as efficient as DocumentFragment
, it can still be a viable option.innerHTML
, but allows you to specify the outer HTML content, which can be more efficient for updating large amounts of content.Keep in mind that these alternatives may have different performance characteristics and may not be suitable for all use cases.
Benchmark Preparation Code
The provided JSON includes the script preparation code ("Script Preparation Code": null
) and HTML preparation code ("Html Preparation Code": "<div id=\"viewer\"></div>"
). These codes are used to set up the benchmark environment, but their contents are not relevant to the performance comparison.