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];
}
for (let i = 0; i < 10000; i++){
let s = "testtesttesttesttest" + obj[1] + " - ";
}
for (let i = 0; i < 10000; i++){
let s = `testtesttesttesttest ${obj[1]} - `;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Concatenation | |
Template strings | |
Concatenating strings with template strings | |
Concatenation without substring call | |
Concat | |
Template |
Test name | Executions per second |
---|---|
Concatenation | 276.7 Ops/sec |
Template strings | 340.1 Ops/sec |
Concatenating strings with template strings | 308.5 Ops/sec |
Concatenation without substring call | 341.5 Ops/sec |
Concat | 1721.5 Ops/sec |
Template | 1705.1 Ops/sec |
Let's break down the provided benchmark and its various test cases.
Benchmark Overview
The benchmark measures the performance of different ways to concatenate strings in JavaScript. The benchmarks compare the execution speed of six approaches:
+
operatorsubstring()
methodLibrary
There is no specific JavaScript library used in this benchmark. The test cases focus solely on the differences between various string concatenation approaches.
Special JS Features or Syntax
The following special JS feature or syntax is used:
Benchmark Test Cases
The six test cases measure the performance of different approaches:
+
operator.substring()
method when removing characters from the end of the string.+
operator.Pros and Cons
Each approach has its pros and cons:
Other Alternatives
Alternative approaches to string concatenation include:
String.prototype.split()
and String.prototype.join()
Array.prototype.map()
and Array.prototype.join()
Buffer
or TypedArray
for efficient, low-level string operationsIn conclusion, this benchmark helps evaluate the performance of different string concatenation approaches in JavaScript, highlighting the importance of choosing the most suitable method based on the specific use case and target audience.