<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
function randomIntFromInterval(min, max) { // min and max included
return Math.floor(Math.random() * (max - min + 1) + min)
}
var tabl = Array.from({ length: 10000 }).map((value, i) => ({ id: i, value: randomIntFromInterval(0, i) }))
const [a, b] = _.partition(tabl, e => e.value % 2)
const a = _.remove(tabl, e => e.value % 2)
tabl = [tabl, a]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash partition | |
lodash remove |
Test name | Executions per second |
---|---|
lodash partition | 6260.9 Ops/sec |
lodash remove | 5708.4 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared, and their pros and cons.
Benchmark Overview
The benchmark compares two approaches: lodash partition
and lodash remove
. The test case uses an array of 10,000 objects with random values. The objective is to determine which approach is faster for these specific operations.
Test Case 1: Lodash Partition
const [a, b] = _.partition(tabl, e => e.value % 2)
Lodash partition
returns two arrays: one containing elements that pass the test (in this case, values with even numbers) and another containing elements that fail the test. The resulting arrays are assigned to a
and b
.
Test Case 2: Lodash Remove
const a = _.remove(tabl, e => e.value % 2)
tabl = [...tabl, ...a]
Lodash remove
returns an array of elements that fail the test (values with odd numbers). The resulting array is assigned to a
, and then the original array is merged with the removed elements using the spread operator (...
) to form a new array.
Library: Lodash
Lodash is a popular JavaScript utility library that provides a collection of helper functions for common tasks, such as:
In this benchmark, Lodash is used to implement the partition
and remove
functions. The library's purpose is to provide a standardized way to perform these operations, making it easier to write efficient and consistent code.
Pros and Cons
Both approaches have their advantages and disadvantages:
Lodash Partition:
Pros:
Cons:
Lodash Remove:
Pros:
Cons:
...
spread operatorOther Considerations
When choosing between these approaches, consider the following factors:
Alternatives
If you don't want to use Lodash, you can implement the partition
and remove
functions using standard JavaScript techniques. Here's an example of how you might implement lodash remove
without the library:
function remove(arr, predicate) {
return arr.filter(predicate).map((item) => !predicate(item));
}
Keep in mind that this implementation is less efficient than Lodash's optimized version.
In summary, the benchmark compares two approaches using Lodash: partition
and remove
. While both have pros and cons, Lodash provides a standardized way to perform these operations, making it easier to write efficient code.