<!--your preparation HTML code goes here-->
const a = "hello "
for(i=0; i<10; i++){
a += "world"
}
let a = "hello "
for(i=0; i<10; i++){
a += "world"
}
let a
for(i=0; i<10; i++){
`${a} world`
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
concat | |
template string |
Test name | Executions per second |
---|---|
concat | 4855460.5 Ops/sec |
template string | 5493755.0 Ops/sec |
The provided benchmark is designed to compare two different methods of concatenating strings in JavaScript: classical concatenation using the +
operator and template literals.
Concatenation Using the +
Operator:
let a = "hello "
for (i = 0; i < 10; i++) {
a += "world"
}
concat
+
operator to append "world" to the string variable a
in each iteration of the loop.Using Template Literals:
let a
for (i = 0; i < 10; i++) {
`${a} world`
}
template string
`
) for string interpolation, which allows expressions to be embedded directly within the string.Concatenation Using the +
Operator:
Using Template Literals:
The benchmark results indicate executions per second for both methods on a specific setup (Chrome 134 running on macOS):
From these results, it is evident that using template literals provides better performance in this specific case.
There are several alternatives for string concatenation and manipulation in JavaScript aside from the tested methods:
Array Join Method:
join()
. This can be especially effective for many concatenations.let parts = ["hello"];
for (i = 0; i < 10; i++) {
parts.push("world");
}
let a = parts.join(" ");
StringBuilder Libraries:
StringBuilder.js
can be used to provide a more efficient string concatenation method similar to the StringBuilder in languages like Java.Using reduce
on Arrays:
let a = ["hello", "world"].reduce((acc, curr) => acc + " " + curr);
Template Strings with Tagged Functions:
In this benchmarking exercise, it is shown that although the traditional concatenation using the +
operator is intuitive, leveraging template literals can yield better performance, particularly in modern JavaScript environments. Additionally, considering alternative methods can provide further optimizations depending on the specific use case and performance needs. For developers, using the right string concatenation method can enhance both performance and code readability, making it essential to choose the most appropriate approach based on the application context.