var str = ''
var chars = 'abcdefghijklmnoprstuwxyz'
while (str.length < 100) str += chars[ Math.floor( Math.random() * chars.length ) ]
var strarr = []
var chars = 'abcdefghijklmnoprstuwxyz'
while (strarr.length < 100) strarr.push(chars[ Math.floor( Math.random() * chars.length ) ])
var str = strarr.join('')
var str = ''
var chars = 'abcdefghijklmnoprstuwxyz'
while (str.length < 100) str = `${str}${chars[ Math.floor( Math.random() * chars.length ) ]}`
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
+= | |
array joining | |
template strings |
Test name | Executions per second |
---|---|
+= | 448047.9 Ops/sec |
array joining | 319155.3 Ops/sec |
template strings | 455964.1 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Overview
The provided benchmark measures the performance of three different ways to concatenate strings in JavaScript:
string +=
join()
${}
)Options Compared
Each option has its own pros and cons:
string +=
: This approach is simple and widely supported, but it's also inefficient because each concatenation creates a new string object in memory.join()
: This approach uses an array to store characters and then joins them together. It's more efficient than string +=
because it avoids creating multiple string objects in memory.${}
): This approach uses a template literal to create a new string object that includes the concatenated characters. It's more efficient than string +=
because it avoids creating multiple string objects in memory and can handle expressions inside the string.Library Usage
None of the options require a specific library, but they may rely on built-in JavaScript features or methods.
join()
: This option uses the join()
method, which is a built-in JavaScript method.${}
): This option uses template literals, which are a feature introduced in ECMAScript 2015 (ES6).Special JS Features
None of the options use special JavaScript features or syntax that would require additional explanation.
Alternative Approaches
Other approaches to concatenating strings in JavaScript include:
concat()
method: This approach is similar to array joining using join()
, but it uses the concat()
method instead.): This approach is similar to template literals, but uses backticks (
) instead of curly brackets ({}
).Example benchmark code for these alternative approaches:
// Concat()
var str = '';
while (str.length < 100) str += chars[ Math.floor( Math.random() * chars.length ) ];
// String interpolation with backticks
var str = ``;
while (str.length < 100) str += chars[ Math.floor( Math.random() * chars.length ) ];
Keep in mind that these alternative approaches may have similar performance characteristics to the options compared, but their exact behavior might vary depending on the specific JavaScript engine and environment used.