This article looks at which is the fastest in between Handlebars and ES6 Template Literals.

TL;DR

For my simple example and with node v5.6.0, I have found that ES6 Template literals are up to 4 times faster than Handlebars.

Code

Test Template

For these tests, I have chosen to use the basic example from the Handlebars website.

The aim is to compile:

<div class="entry">
<h1>{{title}}</h1>
<div class="body">
{{body}}
</div>
</div>

With the data being:

{title: "My New Post", body: "This is my first post!"}

We will then compare the execution time when compiling this template 10000 times.

Handlebars code

Install Handlebars with npm:

$ npm install --save handlebars

Full test code:

const Handlebars = require('handlebars');

// Create a string with the Template
const handlebarsTemplateSource = "<div class=\"entry\">/n<h1>{{title}}</h1>/n<div class=\"body\">/n{{{body}}}/n</div>/n</div>";

// Compile the template source to create the template function
const handlebarsTemplate = Handlebars.compile(handlebarsTemplateSource);

// Initialize the data
const data = {title: "My New Post", body: "This is my first post!"};

let results = [];

// Perf test start
console.time("Handlebars");

for(let i = 0; i < 10000; i = i + 1) {
// Evaluate the template
results.push(handlebarsTemplate(data));
}

// Perf test end
console.timeEnd("Handlebars");

On my machine the code executes at an average speed of 20.113ms.

ES6 Template Literals

The idea of a literal template is to use an arrow function with ES6’s string interpolation capabilities.

Here is an example of a simple ES6 template literal

var template = data => `<div>${data}</div>`;

The Handlebars equivalent would be:

var source = "<div>{{data}}</div>";
var template = Handlebars.compile(source);

You can read more about ES6 Template literals here. But in the meantime here is the full performance test code:

// ES6 Template Literal Definition
const template = data => `<div class="entry">
<h1>${data.title}</h1>
<div class="body">
${data.body}
</div>
</div>`;

// Initialize the data
const data = {title: "My New Post", body: "This is my first post!"};

let results = [];

// Perf test start
console.time("Handlebars");

for(let i = 0; i < 10000; i = i + 1) {
// Evaluate the template
results.push(template(data));
}

// Perf test end
console.timeEnd("Handlebars");

On my machine the code executes at an average speed of 5.007ms. That is 4 time faster than Handlebars.

This is quite good news I think as it means I will now start using this native ES6 feature instead of an external library. Have you experienced something similar ? Let me know in the comments.