<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var size = 10000;
_.range(size);
Array.from(new Array(size), (_, i) => i);
[Array(size).keys()]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash range | |
array from | |
keys spread |
Test name | Executions per second |
---|---|
lodash range | 56884.2 Ops/sec |
array from | 3733.2 Ops/sec |
keys spread | 8183.7 Ops/sec |
Benchmark Explanation
The provided benchmark measures the performance of three different approaches to create an array with a specified size in JavaScript:
_.range()
: This function returns an array of numbers from 0 to the specified size minus one.Array.from(new Array(size), (_, i) => i)
: This method creates a new array by mapping the callback function to each element in the new Array(size)
.[...Array(size).keys()]
: This syntax uses the spread operator (...
) and the keys()
method of an array to create a new array with the keys of the original array.Options Compared
The three options are compared in terms of their performance, which is measured by the number of executions per second.
Pros and Cons of Each Approach
_.range()
:Array.from(new Array(size), (_, i) => i)
:[...Array(size).keys()]
:keys()
method.Library Usage
The benchmark uses the Lodash library, which provides a simple and convenient way to create arrays with a specified size. The _.range()
function is a part of the Lodash library.
Special JS Feature/Syntax
None mentioned in this specific benchmark.
Other Alternatives
If you need to create an array with a specified size in JavaScript, other alternatives include:
Array.from()
method with a generator function or another closure.Note that the choice of approach depends on the specific use case and performance requirements.