new Array(500)
Array.from({ length: 500 })
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
new Array() | |
Array.from() |
Test name | Executions per second |
---|---|
new Array() | 3956551.8 Ops/sec |
Array.from() | 80311.7 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
What is being tested?
The provided benchmark tests two approaches to creating filled arrays:
new Array(500)
: This method creates an array with 500 elements, all initialized to undefined
.Array.from({ length: 500 })
: This method creates a new array by converting the object { length: 500 }
into an array.Options being compared
The two options are compared in terms of their performance, which is measured by the number of executions per second (ExecutionsPerSecond).
Pros and Cons of each approach
new Array(500)
:Array.from({ length: 500 })
:Array.from()
method in JavaScript engines. This method also avoids creating unnecessary objects or garbage.Array.from()
method in older browsers or environments.Library used
In this benchmark, there is no explicit library being tested. However, the Array.from()
method relies on a feature introduced in ECMAScript 2015 (ES6) and has been widely supported by modern browsers since then.
Special JS feature/syntax
The use of Array.from({ length: 500 })
requires knowledge of ES6 features, specifically the spread operator ({ ... }
) and the Array.from()
method. This syntax is not widely supported in older JavaScript environments or browser versions prior to Chrome 33 (released in 2015).
Other alternatives
If new Array(500)
were not being used, other alternative approaches could include:
[...new Array(500)]
Array()
constructor and then filling it with valuesHowever, these alternatives are not being tested in this specific benchmark.
I hope this explanation helps software engineers understand what's happening behind the scenes of this JavaScript microbenchmark!