<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var nTimes = 1000
var func = (i) => i * Math.random()
_.times(nTimes,func)
Array.from({length: nTimes},(_,i) => func(i))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash times | |
Array.from |
Test name | Executions per second |
---|---|
lodash times | 12935.2 Ops/sec |
Array.from | 6776.6 Ops/sec |
Let's break down the benchmark and its results.
What is being tested?
The benchmark tests two approaches to iterate nTimes
number of times, where each iteration calls a function func
. The two approaches are:
_times
functionArray.from
with a callback functionOptions compared:
_times
function: This is a utility function that takes three arguments: the number of times to iterate (nTimes
), and a callback function (func
). It returns an array where each element is the result of calling func
in each iteration.Array.from
with a callback function: This method creates a new array from an existing array-like object (in this case, an empty object) by repeatedly applying a callback function to create new elements.Pros and Cons:
_times
function:nTimes
Array.from
with a callback function:_times
Library and syntax:
_times
function: This function uses Lodash's internal implementation, which is optimized for performance. The callback function passed to _times
is called in each iteration, returning a value that is collected into an array.Array.from
with a callback function: This method uses the Array.prototype.forEach
method internally, which calls the provided callback function on each element of the array-like object.Special JS feature or syntax:
None mentioned in this benchmark.
Other alternatives:
If you need to iterate over a large number of times, you could also consider using:
reduce()
method: While not directly applicable here, reduce()
can be used in conjunction with _times
or Array.from
to perform more complex operations.Keep in mind that the choice of approach depends on your specific use case and performance requirements.