var obj = {0:"test",1:"test",2:"test",3:"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]}`;
}
for (let i = 0; i < 10000; i++){
let s = "";
for (let j = 0; j < 2; j++){
s += obj[j] + " - ";
}
s += `${obj[2]} - `;
s += `${obj[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 | |
Concatenating strings with template strings | |
Concatenation without substring call |
Test name | Executions per second |
---|---|
Concatenation | 267.6 Ops/sec |
Template strings | 322.1 Ops/sec |
Concatenating strings with template strings | 293.5 Ops/sec |
Concatenation without substring call | 326.5 Ops/sec |
Let's dive into the benchmark and explore what's being tested.
Benchmark Overview
The benchmark is comparing four different approaches to concatenate strings in JavaScript:
+
operatorsubstring()
Options Being Compared
The benchmark is comparing the performance of these four approaches on a specific use case:
obj
with 4 string propertiesPros and Cons of Each Approach
+
operator:substring()
:substring()
overhead.Library Used
There is no explicit library used in this benchmark. The script uses native JavaScript features to create the object obj
and concatenate strings.
Special JS Feature or Syntax
The benchmark uses ES6 template literals (${...}
) for the "Template strings" approach, which was introduced in ECMAScript 2015. Other approaches use standard string concatenation using the +
operator.
Other Alternatives
If you're interested in exploring other alternatives, consider:
Keep in mind that the specific performance characteristics of these approaches may vary depending on your use case, browser, and JavaScript engine.