function template(html) {
var t = document.createElement('template');
t.innerHTML = html;
return t.content.firstChild;
}
function div(html) {
var t = document.createElement('div');
t.innerHTML = html;
return t.firstChild;
}
var html = '<div><div class="col-md-1"></div><div class="col-md-4"><a></a></div><div class="col-md-1"><a><span class="glyphicon glyphicon-remove" aria-hidden="true" /></a></div><div class="col-md-6" /></div>';
template(html).cloneNode(true);
div(html).cloneNode(true);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Template | |
Div |
Test name | Executions per second |
---|---|
Template | 96019.2 Ops/sec |
Div | 95163.6 Ops/sec |
Overview
MeasureThat.net is a website that allows users to create and run JavaScript microbenchmarks. The provided JSON represents a benchmark definition, which tests the performance of two different approaches: using a template
element versus a regular div
element.
Benchmark Definition JSON
The benchmark definition JSON contains:
Name
: The name of the benchmark, which is "template vs div (fixed 2)".Description
: An empty description field, indicating that no detailed description is provided for this benchmark.Script Preparation Code
: A JavaScript code snippet that defines two functions: template(html)
and div(html)
. Both functions create an element from the provided HTML string and return its first child node. The template
function uses a <template>
element, while the div
function uses a regular <div>
element.Html Preparation Code
: An empty field, indicating that no additional HTML preparation code is required.Individual Test Cases
The benchmark definition includes two individual test cases:
"Benchmark Definition": "template(html).cloneNode(true);",
"Benchmark Definition": "div(html).cloneNode(true);,"
These test cases compare the performance of cloning a node from both the template
and div
approaches.
Options Compared
The benchmark compares the performance of two options:
<template>
element to create an element from the provided HTML string.<div>
element to create an element from the provided HTML string.Pros and Cons of Each Approach
template
element.Library and Purpose
The benchmark uses the cloneNode(true)
method, which is a part of the DOM API. The purpose of this method is to create a deep copy of an element, including its children and attributes, without losing any data.
Special JS Feature or Syntax
There are no special JavaScript features or syntax used in this benchmark that require explanation.
Other Alternatives
If you need to compare performance between creating elements using template
and div
, there are other alternatives:
Keep in mind that these alternatives may have different trade-offs in terms of performance, complexity, and compatibility with different browsers and devices.