var name = "John";
var age = "30";
for (let i = 0; i < 80; ++i) {
let result = age + ": 1, " + name + ": someItem";
}
for (let i = 0; i < 80; ++i) {
let result = "".concat(age, ": 1, ", name, ": someItem");
}
for (let i = 0; i < 80; ++i) {
let result = `${age}: 1, ${name}: someItem`;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
using plus operator | |
using concat function | |
using template literals |
Test name | Executions per second |
---|---|
using plus operator | 210779.0 Ops/sec |
using concat function | 176505.8 Ops/sec |
using template literals | 205964.8 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Overview
The benchmark measures the performance of three different ways to concatenate strings in JavaScript:
+
operator (also known as string concatenation)concat()
function${...}}
)The benchmark aims to find the most efficient method for concatenating four strings.
Options Compared
Here's a brief summary of each option:
+
operator: This is a basic string concatenation using the +
symbol between two or more strings. It creates a new string by combining the existing strings.concat()
function: This is a method provided by the String
prototype that concatenates two or more strings. It returns a new string object.+
operator since it avoids creating temporary objects.concat()
method, which can add overhead.) and placeholders (e.g.,
${variable}`) to insert values into strings.+
operator or concat()
function, as it avoids creating temporary objects.Library Used
In this benchmark, no external library is required. All three options use built-in JavaScript features.
Special JS Feature or Syntax
Template literals are a special feature introduced in ECMAScript 2015 (ES6). They provide a more readable way to concatenate strings with values inserted into them.
Considerations
When choosing an approach for string concatenation, consider the following:
concat()
function might be more efficient than using the +
operator.Other Alternatives
Besides the three options mentioned in the benchmark:
String.prototype.replace()
with a callback function to concatenate strings, which is less efficient due to regular expression parsing overhead.Array.prototype.join()
to concatenate an array of strings, which requires creating an intermediate array and joining it into a single string.Keep in mind that these alternatives are generally less optimal than the three options mentioned in the benchmark.