var name = "name";
var id = "id";
let result;
for (let i = 0; i < 80; ++i) {
result += id + ": 1, " + name + ": someItem";
}
console.log(result);
return result.length;
let result;
for (let i = 0; i < 80; ++i) {
result += "".concat(id, ": 1, ", name, ": someItem");
}
console.log(result);
return result.length;
let result;
for (let i = 0; i < 80; ++i) {
result += `${id}: 1, ${name}: someItem`;
}
console.log(result);
return result.length;
--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 | 41692.6 Ops/sec |
using concat function | 40907.7 Ops/sec |
using template literals | 41354.3 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Definition
The benchmark measures which approach is best for concatenating four strings in JavaScript. The script preparation code sets two variables, name
and id
, to string values. The HTML preparation code is empty, indicating that this benchmark is purely focused on JavaScript performance.
Options Compared
Three options are being compared:
+
): This approach concatenates strings using the +
operator.concat()
function: This approach uses the built-in concat()
method to concatenate strings.${}
): This approach uses a feature introduced in ECMAScript 2015 (ES6) called template literals.Pros and Cons of Each Approach
+
):concat()
function:${}
):Library Usage
The concat()
function is a built-in JavaScript function that concatenates strings. It's not a separate library.
Special JS Feature/Syntax
Template literals (${}
) were introduced in ECMAScript 2015 (ES6). They provide a concise way to embed expressions inside string literals.
Benchmark Results
The benchmark results show the performance of each approach:
concat()
function: Slower than template literals, but faster than using the plus operator.Alternatives
If you're looking for alternative approaches to concatenating strings in JavaScript, consider:
Keep in mind that the best approach depends on your specific use case, performance requirements, and personal preference.