<script src="https://cdn.jsdelivr.net/npm/lodash/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 = [];
var rest = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i] % 2 === 0){
met.push(arr[i]);}
else {
rest.push(arr[i]); }
}
var rest = [];
arr = arr.filter(e => {
if (e % 2 === 0) {
return true;
}
else {
rest.push(e);
return false;
}
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash | |
loop push | |
filter |
Test name | Executions per second |
---|---|
Lodash | 286436.2 Ops/sec |
loop push | 9422.9 Ops/sec |
filter | 708961.2 Ops/sec |
Let's break down the provided JSON and explain what is tested in each benchmark.
Benchmark Definition
The benchmark definition is a JavaScript code snippet that defines how to split an array into two parts based on a condition. The three benchmarks compare different approaches:
_.partition
function from the Lodash library, which takes two arguments: the array to be split and a callback function that returns a boolean value indicating whether each element should be included in the first part or not.met
) and another for elements that don't (rest
). The elements are pushed into their respective arrays using loops.filter
method of the array to create two new arrays: one with elements satisfying the condition and another with elements not satisfying it.Options Comparison
Here's a brief overview of each option, including their pros and cons:
partition
function, and can create new arrays unnecessarily.Library Usage
The benchmark uses the Lodash library for its partition
function. Lodash is a popular JavaScript utility library that provides various functions for tasks such as array manipulation, object merging, and more.
Special JS Features or Syntax
There are no special features or syntax used in this benchmark that are not standard JavaScript. However, some readers might be familiar with the use of arrow functions (e => { ... }
) which were introduced in ECMAScript 2015 (ES6).
Other Alternatives
If you'd like to explore alternative approaches, here are a few options:
Array.prototype.filter()
or Array.prototype.reduce()
, which might be slightly faster than the filter
method used in this benchmark.lodash-es
or other alternatives to Lodash, such as ramda
.Keep in mind that these alternatives may have different performance characteristics, readability, and maintainability compared to the approaches used in this benchmark.