var s1 = "foo";
var s2 = "foo 12312";
let n1 = Array.from(s1);
let n2 = Array.from(s2);
let n1 = s1.split('');
let n2 = s2.split('');
let n1 = [s1];
let n2 = [s2];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.from | |
string split | |
spread operator |
Test name | Executions per second |
---|---|
Array.from | 4667531.5 Ops/sec |
string split | 38371076.0 Ops/sec |
spread operator | 21633162.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Overview
The benchmark compares three approaches for creating an array from a string:
Array.from()
: a built-in method that creates an array from an iterable object, such as a string.split()
method with an empty string (''
) as the separator.Options Comparison
Let's analyze each approach and their pros and cons:
Array.from()
:split()
.Array.from()
.Library Usage
In this benchmark, the Array.from()
method is a built-in JavaScript function. It doesn't rely on any external libraries.
Special JS Features/Syntax
The benchmark uses two special features:
...
): used in the spread operator approach to create a new array by spreading elements of an existing array.Array.from()
.Other Alternatives
If you need to create an array from a string without using any built-in methods or libraries, you can consider the following alternatives:
map()
and concat()
: creating an array by mapping each character in the string to itself and concatenating the results.for
loop and adding elements to an array.Here's a simple example of the first alternative:
let n1 = [];
for (let i = 0; i < s1.length; i++) {
n1.push(s1[i]);
}
And here's an example of the second alternative:
let n1 = [];
for (let i = 0; i < s1.length; i++) {
for (let j = 0; j <= i; j++) { // Include the string itself as an element
n1.push(s1[j]);
}
}
Keep in mind that these alternatives are generally less efficient and more verbose than using Array.from()
or the spread operator.