new Array(200000).fill({ a: 1}).map(function(value, index) { return {value, id: index}})
Array.from({length: 200000}, function(_v, index) { return { a: 1, id: index}})
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.fill | |
Array.from |
Test name | Executions per second |
---|---|
Array.fill | 116.8 Ops/sec |
Array.from | 139.2 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Definition
The benchmark is designed to compare two approaches for creating an array of objects with dynamic data: Array.fill
and Array.from
. The benchmark definition provides both methods, but they differ in their input data. For Array.fill
, a new array of 200,000 elements is created using the fill()
method, while for Array.from
, an object with a length of 200,000 is used as the input.
Options Compared
The two options being compared are:
Array.fill()
: A method that creates a new array by repeating the provided value (in this case, an object with a: 1
) to fill the entire array.Array.from()
: A method that creates a new array from an iterable or an array-like object (in this case, the object with a length of 200,000).Pros and Cons
Here are some pros and cons of each approach:
Array.fill()
:Array.from()
:Array.fill()
for very large arrays.Library
Neither of these options uses a library. They are built-in methods in JavaScript.
Special JS Feature/Syntax
There is no special JS feature or syntax used in this benchmark. It's purely focused on comparing the performance of two built-in methods.
Other Considerations
When running benchmarks like this, it's essential to consider factors that might affect performance, such as:
Alternatives
If you're looking for alternatives to Array.fill()
and Array.from()
, consider the following options:
Array.prototype.map()
: While not suitable for creating an array of fixed-size elements, it's often used in conjunction with other methods (like fill()
or from()
) to process arrays.Array.prototype.reduce()
: Similar to map()
, but it's more commonly used for aggregation and processing.For creating arrays from existing iterables, consider using libraries like Lodash (_.times()
) or Ramda (ramda.times()
). However, keep in mind that these libraries add overhead, so be cautious when including them in performance-critical code.