var name = "name";
var id = "id";
for (let i = 0; i < 80; ++i) {
let result = id + ": 1, " + name + ": someItem";
}
for (let i = 0; i < 80; ++i) {
let result = "".concat(id, ": 1, ", name, ": someItem");
}
for (let i = 0; i < 80; ++i) {
let result = `${id}: 1, ${name}: someItem`;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
using plus operator | |
using concat function | |
using template literals |
Test name | Executions per second |
---|---|
using plus operator | 184714.2 Ops/sec |
using concat function | 90758.4 Ops/sec |
using template literals | 179995.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
Benchmark Definition
The provided JSON represents a benchmark that tests three different approaches to concatenating strings in JavaScript:
+
operator (plus operator)concat()
function${}
)Script Preparation Code
The script preparation code is:
var name = "name";
var id = "id";
This sets two variables, name
and id
, to string values.
Html Preparation Code
The HTML preparation code is empty (i.e., null
). This suggests that the benchmark doesn't require any specific HTML structure or content.
Individual Test Cases
There are three test cases:
for (let i = 0; i < 80; ++i) {
let result = id + ": 1, " + name + ": someItem";
}
This code uses the +
operator to concatenate the strings id
, ": 1, ",
and name
, with the string "someItem"
.
for (let i = 0; i < 80; ++i) {
let result = "" + id + ": 1, " + name + ": someItem";
}
This code uses the concat()
function to concatenate strings.
for (let i = 0; i < 80; ++i) {
let result = `${id}: 1, ${name}: someItem`;
}
This code uses template literals (${}
) to concatenate the strings id
, ": 1, ",
and name
, with the string "someItem"
.
Benchmark Results
The latest benchmark results show the performance of each approach on a specific browser (Safari 16) and device platform (Desktop):
Library Used
None of the test cases use any external libraries.
Special JS Features or Syntax
There are no special JavaScript features or syntax used in this benchmark (e.g., let
declarations, arrow functions, async/await
, etc.).
Other Alternatives
If you're interested in exploring other alternatives for string concatenation in JavaScript, here are a few:
+
operator with string formatting: id + ": 1, " + name + ": someItem"
. This approach is similar to the plus operator method but allows for more formatting options.String.prototype.replace()
and String.prototype.split()
: This approach involves splitting the strings into substrings using a regex pattern, replacing the substring with the desired concatenation, and then joining them back together.Keep in mind that these alternatives may not always be faster or more efficient than the approaches tested in this benchmark. The performance results can vary depending on specific use cases, browser versions, and device platforms.