const count = 10000;
for (let i = 0; i < count; ++i) {
let result = i
result += 'px';
}
for (let i = 0; i < count; ++i) {
let result = i
result = ''.concat(result, 'px');
}
for (let i = 0; i < count; ++i) {
let result = i
result = `${result}px`;
}
--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 | 87032.7 Ops/sec |
using concat function | 1674.7 Ops/sec |
using template literals | 3436.4 Ops/sec |
The provided benchmark focuses on measuring the performance of three different methods for concatenating strings in JavaScript. Specifically, it evaluates the efficiency of concatenating an integer converted to a string with the suffix 'px' using the following three approaches:
+
)String.concat
Function`${}`
)Using Plus Operator (+
)
Using String.concat
Function
Using Template Literals (`${}`
)
In this benchmark, no external libraries are used; all three methods are native JavaScript features. Specifically, Template Literals is a feature introduced in ES6 (ECMAScript 2015) that enables a more flexible way to construct strings.
When considering alternatives to these methods:
Array Join: Concatenating strings using an array and the join
method (i.e., array.join('')
) can be more efficient when constructing a string from many pieces, especially within loops. This approach avoids the issues of repeated string allocations.
String Interpolation Libraries: In some cases, libraries like lodash
or sprintf-js
can be used for formatted string construction, but they usually come at a cost due to additional overhead.
In summary, when opting for string concatenation in JavaScript, the choice between these methods often hinges on the need for performance versus readability. The benchmark clearly shows that for simple and frequent concatenations, the plus operator (+
) is the standout choice, while Template Literals and String.concat
offer advantages in readability and structure.