<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var arr = [];
for (i = 0; i < 1000; i++) {
arr[i] = i;
}
var [met, rest] = _.partition(arr, function(i) { return i % 2 === 0 });
var [met, rest] = arr.reduce(function([p1, p2], i) { return i % 2 === 0 ? [[p1, i], p2] : [p1, [p2, i]] }, [[], []])
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash | |
Native reduce |
Test name | Executions per second |
---|---|
Lodash | 399444.4 Ops/sec |
Native reduce | 7174.7 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
Benchmark Overview
The provided JSON represents two test cases for measuring the performance of partitioning an array in JavaScript. The first test case uses Lodash, a popular utility library for functional programming tasks, while the second test case uses native JavaScript methods.
Options Compared
In this benchmark, we're comparing the performance of:
partition
method: This function takes two arguments: the input array and a callback function that returns a boolean value indicating whether an element should be included in the first partition or not.reduce
method: This method applies a reduction function to each element of an array, accumulating a value across all elements.Pros and Cons
partition
Pros:
Cons:
reduce
Pros:
Cons:
forEach
instead of reduce
).Library: Lodash
Lodash is a utility library that provides a wide range of functional programming helpers. The partition
method is one of these helpers, allowing you to split an array into two partitions based on a condition. In this benchmark, Lodash's partition
method is used to divide the input array into two parts: elements where the index is even and elements where it's odd.
Special JS Feature/Syntax
In this benchmark, we're using the ES6 destructuring assignment syntax (var [met, rest] = ...;
) to extract the first element of the reduced array from the reduce
method. This syntax was introduced in ECMAScript 2015 (ES6) and allows you to destructure arrays into separate variables.
Other Alternatives
If you're looking for alternative ways to partition an array, consider using:
filter()
to create a new array with elements that pass a test.reduce
, you can use forEach()
in combination with map()
or another function to achieve similar results.Keep in mind that these alternatives may have different performance characteristics and may require more code.