<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.innerHTML = newDiv;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
createElement | |
template string |
Test name | Executions per second |
---|---|
createElement | 188241.5 Ops/sec |
template string | 309717.0 Ops/sec |
Let's break down the provided benchmark definition and test cases to understand what's being tested.
Benchmark Definition
The benchmark is comparing two approaches for creating HTML elements: document.createElement
and string template literals (also known as template strings).
Script Preparation Code
var i, imax;
var div = document.getElementById('testdiv');
This code snippet prepares the test environment by getting a reference to an HTML element with the id "testdiv" using the document.getElementById
method.
Html Preparation Code
<div id="testdiv">
<div class="unique">test</div>
</div>
This is the HTML structure that will be used as input for the benchmark tests. It contains a single <div>
element with a class of "unique" and text content "test".
Individual Test Cases
There are two test cases:
var newDiv = document.createElement('div');
newDiv.classList.add('unique');
newDiv.innerText = 'test';
div.innerHTML = newDiv;
This test creates a new <div>
element using document.createElement
, adds the "unique" class to it, sets its text content to "test", and then appends the new element's innerHTML to the original <div>
element.
var newDiv = `<div class="unique">test</div>`;
div.innerHTML = newDiv;
This test uses a template literal (string template) to create the HTML content of the new <div>
element, which is then appended to the original <div>
element using div.innerHTML
.
Library
None of the tests explicitly use any external libraries. However, it's worth noting that some modern JavaScript engines and browsers may have additional features or optimizations that are not relevant to this specific benchmark.
Special JS Features/Syntax
The test cases do not specifically target any special JavaScript features or syntax. They focus on comparing two straightforward approaches for creating HTML elements.
Pros and Cons of Different Approaches
Here's a brief summary:
createElement
for large-scale templates or complex layouts.Other Alternatives
If you're looking for alternative approaches to create HTML elements in JavaScript, consider the following:
template string
, but requires setting the element's content using a string literal.When choosing an approach, consider factors such as performance requirements, code readability, and maintainability. The benchmark provided by MeasureThat.net should help you understand the relative performance characteristics of each method in a controlled environment.