let str = "";
const sArr = [];
const limit = 10000;
for (let i = 0; i < limit; i++) {
str += "String concatenation. ";
}
let str = "";
const sArr = [];
const limit = 10000;
for (let i = 0; i < limit; i++) {
sArr[i] = "String concatenation. ";
}
str = sArr.join("");
let str = "";
const sArr = [];
const limit = 10000;
for (let i = 0; i < limit; i++) {
sArr.push("String concatenation. ");
}
str = sArr.join("");
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
string concatention | |
Array join | |
Array join with push |
Test name | Executions per second |
---|---|
string concatention | 26420.3 Ops/sec |
Array join | 2901.4 Ops/sec |
Array join with push | 2786.9 Ops/sec |
Let's break down the benchmark and explain what is tested, the different approaches compared, their pros and cons, and other considerations.
What is being tested?
The benchmark tests three different ways to concatenate strings in JavaScript:
+=
operator ("String concatenation."
)join()
method on an array of strings (sArr.join("")
)push()
method to add elements to an array and then joining it with join()
(sArr.push("String concatenation.").join("")
)Approaches compared
The three approaches are compared in terms of performance, which is measured by the number of executions per second.
Pros and Cons of each approach:
+=
operator+=
in a loop without clearing the previous string)join()
method on an array of strings+=
operator for large arrayspush()
method to add elements to an array and then joining it with join()
+=
operator for large arraysjoin()
alone (e.g., can insert or remove elements from the middle of the string)Other considerations
+=
operator can lead to poor cache locality due to frequent relocations of the string object.Library usage
None of the benchmark scripts use any external libraries or frameworks. The test code only uses built-in JavaScript features and operators.
Special JS feature/syntax
No special JavaScript features or syntax are used in this benchmark. The code is written in standard JavaScript, using modern syntax and features (e.g., arrow functions, template literals) where applicable.
Alternatives
Other alternatives for string concatenation include:
StringBuilder
object (not available in standard JavaScript)StringBuffer
class to mimic the behavior of a StringBuilder
objectText
API or DOMString
manipulation APIs in some browsers.Note that these alternatives may have different performance characteristics compared to the standard JavaScript approaches tested in this benchmark.