new Array(1000).fill(0).map(() => Math.random())
Array.from({length: 1000}, () => Math.random())
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
new Array(1000) | |
Array.from({length: 1000}) |
Test name | Executions per second |
---|---|
new Array(1000) | 5220.2 Ops/sec |
Array.from({length: 1000}) | 3459.3 Ops/sec |
Overview of the Benchmark
MeasureThat.net is a website that allows users to create and run JavaScript microbenchmarks. The provided benchmark measures the performance difference between creating an array using new Array()
versus using Array.from()
with random data.
What is being tested?
Two test cases are compared:
new Array(1000).fill(0).map(() => Math.random())
.Array.from({length: 1000}, () => Math.random())
.Options being compared
The two approaches are compared in terms of their performance, which is measured by the number of executions per second.
Pros and Cons of each approach
new Array()
:Array.from()
:new Array()
.length
property, which may not be necessary if only an array is needed.Library used
In this benchmark, no specific library is used beyond what is built-in to JavaScript. However, it's worth noting that Array.from()
was introduced in ECMAScript 2015 (ES6) as part of the standard library.
Special JavaScript features or syntax
None are mentioned in this benchmark. Both test cases use basic JavaScript syntax and do not rely on any advanced features or libraries beyond what is built-in to JavaScript.
Other alternatives
There are other ways to create arrays in JavaScript, such as using a for
loop:
const arr = new Array(1000);
for (let i = 0; i < 1000; i++) {
arr[i] = Math.random();
}
Or using Array.prototype.fill()
and Math.random()
:
const arr = new Array(1000).fill(0).map(() => Math.random());
However, these approaches are not what the benchmark is comparing (i.e., new Array()
vs. Array.from()
)