<script src="https://cdn.jsdelivr.net/lodash/4.16.0/lodash.min.js"></script>
var array = _.range(1000);
_.map(_.filter(array, function(n) { return n > 998; }), function(n) { return {test: n}; });
_(array).filter(function(n) { return n > 998; }).map(function(n) { return {test: n}; });
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Strict | |
Lazy |
Test name | Executions per second |
---|---|
Strict | 73444.6 Ops/sec |
Lazy | 1146513.2 Ops/sec |
I'd be happy to help explain the JavaScript benchmark on MeasureThat.net.
Overview
The benchmark measures the performance of two ways of using the Lodash library, which is a popular utility library for JavaScript. The test cases compare the execution speed of two different approaches: "Strict" and "Lazy".
What's being tested?
In the first test case, "map(.filter(array, function(n) { return n > 998; }), function(n) { return {test: n}; });", we have a strict pipeline:
_.filter(array, ...)
applies the filter function to the entire array and returns a new array with only the elements that pass the test._()
is an alias for Lodash's _
function, which returns the value returned by the function passed as its argument..map(...)
applies the mapping function to each element of the filtered array.In contrast, the second test case uses a lazy approach: "(array).filter(...) .map(...)". This pipeline is executed in two steps:
_(array)
returns an object that can be used as a cache, so subsequent calls to this object with the same arguments will return the cached result..filter(...)
applies the filter function to the array..map(...)
applies the mapping function to each element of the filtered array.Pros and Cons
Strict approach:
Lazy approach:
Lodash library
The Lodash library provides several aliases and utility functions that simplify common tasks. In this benchmark, _.map
and _.filter
are used as aliases for Array.prototype.map
and Array.prototype.filter
, respectively.
Other alternatives
There are other ways to achieve the same result without using Lodash:
array.filter(function(n) { return n > 998; }).map(function(n) { return {test: n}; })
In conclusion, this benchmark compares two approaches to applying filter and map functions in Lodash. The strict approach can be faster if the cache is not hit often enough, while the lazy approach reduces overhead by avoiding unnecessary calculations and intermediate results.