var obj = {param1:"test",param2:"test",param3:"test",param4:"test"}
for (let i = 0; i < 10000; i++){
let s = "";
for (let j = 0; j < 4; j++){
s += obj[j] + " - ";
}
s = s.substring(0,s.length - 3);
}
for (let i = 0; i < 10000; i++){
let s = `${obj[0]} - ${obj[1]} - ${obj[2]} - ${obj[3]}`;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Concatenation | |
Template strings |
Test name | Executions per second |
---|---|
Concatenation | 335.1 Ops/sec |
Template strings | 387.1 Ops/sec |
Let's dive into the provided benchmark.
What is being tested?
MeasureThat.net is testing the performance difference between two approaches: concatenating strings using the traditional method (+
) and template literals (template strings). The benchmark script generates two arrays of strings, obj
, and then iterates through a loop 10,000 times. In the traditional method, each string is concatenated by adding the array elements with -
in between, while in the template literal approach, all elements are included in the string using template literals.
Options being compared
The two approaches being tested are:
+
)Other considerations
When using template literals, it's essential to note that the expression inside the backticks must be a valid JavaScript expression, which means you cannot directly concatenate non-numeric values or non-string expressions with -
. Additionally, some older browsers may not support template literals, so it's crucial to test for browser compatibility.
Library used
The benchmark script uses the obj
array as a parameter. It appears to be an example of a real-world data structure, where each element is a string that represents a value.
Special JS feature or syntax
There are no special JavaScript features or syntaxes mentioned in this benchmark. The code only uses standard JavaScript syntax and features.
Now, let's discuss the benchmark results:
The latest benchmark result shows that template literals outperform traditional string concatenation in terms of executions per second.
To gain a better understanding of the performance differences, you can try modifying the obj
array to contain non-string elements or using different data structures. Additionally, consider exploring other optimization techniques, such as reducing the number of iterations or minimizing the scope of variables used in the loop.
Other alternatives
If you're interested in exploring alternative approaches, here are a few options:
Keep in mind that benchmarking is an essential step in optimizing performance-critical code. MeasureThat.net provides a valuable platform for comparing different approaches and identifying areas for improvement.