<table><tbody id="body"></tbody></table>
var rows = [];
for (var i = 0; i < 10000; ++i) {
var row = document.createElement("tr");
var cell = document.createElement("td");
cell.appendChild(document.createTextNode(i));
row.appendChild(cell);
body.appendChild(row);
rows.push(row);
}
var nodes = body.childNodes;
for (var i = 0; i < 10000; ++i) {
body.append(rows[i]);
}
for (var i = 0; i < 10000; ++i) {
body.prepend(rows[i]);
}
for (var i = 0; i < 10000; ++i) {
body.insertBefore(rows[9999 - i], nodes[i]);
}
for (var i = 0; i < 10000; ++i) {
body.appendChild(rows[i]);
}
for (var i = 0; i < 10000; ++i) {
body.insertAdjacentElement("beforeend",rows[i]);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
append | |
prepend | |
insertBefore | |
appendChild | |
insertAdjacentElement |
Test name | Executions per second |
---|---|
append | 260.8 Ops/sec |
prepend | 260.7 Ops/sec |
insertBefore | 6.4 Ops/sec |
appendChild | 309.4 Ops/sec |
insertAdjacentElement | 304.8 Ops/sec |
Measuring the performance of different methods for appending or modifying elements in an HTML table is crucial, especially when dealing with large datasets.
Overview of Benchmark
The provided benchmark measures the execution time of different DOM manipulation methods: append
, prepend
, insertBefore
, appendChild
, and insertAdjacentElement
. It creates a populated table by generating 10,000 rows and appends or modifies them using each method.
Options Compared
append
: Appends an element to the end of its parent container.prepend
: Prepends an element to the beginning of its parent container.insertBefore
: Inserts a node before a specified reference node in the DOM tree.appendChild
: Appends one or more child nodes to the end of the parent node's children list.insertAdjacentElement
: Inserts an element at a specific position relative to its parent element.Pros and Cons
append
: Pros:
Cons:
prepend
: Pros:
insertBefore
: Pros:
appendChild
: Pros:
insertAdjacentElement
: Pros:
Cons:
insertBefore
Library and Syntax Used
There is no explicit library mentioned in the benchmark setup code, but it uses native JavaScript DOM APIs.
Special JS Features or Syntax Used (if any)
None are explicitly used in this benchmark. However, note that using certain advanced features like async/await can affect performance when dealing with large datasets or DOM manipulation.
Other Alternatives
Some alternative approaches could include:
Keep in mind that the best approach often depends on the specific requirements and constraints of your project.