<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;
}
_.partition([], function() { return false });
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 | 282647.9 Ops/sec |
Native reduce | 4897.1 Ops/sec |
Let's break down the provided benchmark and explain what is being tested.
Benchmark Overview
The benchmark compares two approaches to partitioning an array: using Lodash's partition
function versus implementing a native reduction method. The test creates an array of 1000 elements, where each element is a unique integer, and then attempts to partition the array into two parts based on whether the element is even or odd.
Options Compared
The benchmark tests two options:
partition
function: This approach uses Lodash's built-in partition
function to split the array into two parts.Pros and Cons
Here are some pros and cons for each approach:
partition
function:Library Usage
In this benchmark, Lodash is used in two ways:
lodash.min.js
library is loaded via a script tag, which allows the user to easily include the library in their environment.partition
function is called using the _
alias (i.e., _.partition(arr, ...)
) to access the partition
method from Lodash.Special JS Feature/Syntax
None of the benchmark's code uses any special JavaScript features or syntax that requires explanation. Both approaches rely on standard JavaScript array methods and operators.
Other Alternatives
If you're interested in exploring alternative partitioning methods, here are a few options:
filter()
to create two arrays based on the condition: one for elements that pass the test and another for those that don't.map()
to transform the array into two smaller arrays, one for even numbers and one for odd numbers, using slice()
to separate them.In summary, the benchmark provides a simple yet informative comparison between two approaches to partitioning an array: Lodash's partition
function versus a native reduction method.