var test = "bdahjsbfahjdfbahdf"
var test2 = "nfajkdsfnklruiefbruiefhqbgrhbgqlk"
var test3 = "abldfjbafbeirwubfejkwbfkwlfbbdabsjkdblKDBKAJBSDK"
var res = [test, test2, test3].join(" ");
var finalString2 = `${test} ${test2} ${test3}`;
var finalString3 = test + " " + test2 + " " + test3;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
array.join | |
string literal | |
string concatenation |
Test name | Executions per second |
---|---|
array.join | 5202176.0 Ops/sec |
string literal | 8382658.5 Ops/sec |
string concatenation | 8668269.0 Ops/sec |
Measuring the performance of different ways to concatenate strings in JavaScript can be a useful benchmark.
What is being tested?
In this benchmark, three test cases are compared:
+
operator to concatenate strings.${}
) to concatenate strings.join()
method on an array of strings to concatenate them.Options comparison
Here's a brief overview of each option:
+
operator. However, it can lead to performance issues if done frequently, as it creates a new string object on each iteration.Pros and Cons
Here are some pros and cons of each approach:
Library usage
None of the test cases uses any libraries explicitly. However, it's worth noting that template literals rely on a subset of JavaScript features and syntax (e.g., ${}
), which are built into the language and don't require external dependencies.
Special JS feature
The benchmark uses the following special JavaScript feature:
${}
.Alternatives
If you're looking for alternative ways to concatenate strings, here are a few options:
String.prototype.replace()
and concatenating strings: This method can be useful when working with regex patterns.StringBuilder
or other library functions (not recommended in this benchmark): While not used in this example, some libraries like jQuery or React use StringBuilder
-like APIs to concatenate strings.Overall, the benchmark provides a useful comparison of three common ways to concatenate strings in JavaScript. Understanding these options can help developers choose the most efficient and readable approach for their specific use cases.