<div></div>
const div = document.createElement('div')
div.innerHTML = Math.random().toString();
return div.outerHTML;
const div = document.createElementNS('http://www.w3.org/1999/xhtml', 'div')
div.innerHTML = Math.random().toString();
return div.outerHTML;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
createElement | |
createElementNS |
Test name | Executions per second |
---|---|
createElement | 150263.7 Ops/sec |
createElementNS | 185567.7 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared, and their pros and cons.
Benchmark Overview
The benchmark is designed to compare two approaches for creating HTML elements in JavaScript: document.createElement
and document.createElementNS
. The test case uses a simple HTML div element with random inner text.
What's Being Tested?
Two test cases are run:
createElement
: This test creates an HTML element using the standard createElement
method, which returns an element that can be appended to a document without specifying its namespace.createElementNS
: This test creates an HTML element using the createElementNS
method, which returns an element with a specific namespace (in this case, http://www.w3.org/1999/xhtml
). The purpose of creating elements with namespaces is to enable features like XML serialization and schema validation.Options Compared
The two approaches are compared in terms of performance, specifically the number of executions per second.
Pros and Cons
Here's a brief overview of each approach:
document.createElement
:document.createElementNS
:Library Used
There is no library explicitly mentioned in the benchmark. However, it's worth noting that createElementNS
requires a specific namespace to be specified, which might involve using a namespace resolution mechanism or registry.
Special JS Feature/ Syntax
The benchmark uses JavaScript's Math.random().toString()
function to generate random inner text for the div element. This is not a special feature per se, but rather a simple way to introduce variation in the test results.
Other Alternatives
In theory, other approaches could be used to create HTML elements, such as:
template
from the micro-template
library.However, these alternatives are not explicitly tested in this benchmark.
Benchmark Preparation Code
The provided Html Preparation Code
is simple and focuses on creating an empty div element (<div></div>
). The Script Preparation Code
is empty, which means no additional setup or initialization code is required before running the test cases.