<script src="lodash.js"></script>
var listOfObjects_1 = [{id: 1, name: '1'}, {id: 2, name: '2'}, {id: 5, name: '5'}]
var listOfObjects_2 = [{id: 1, name: '1'}, {id: 2, name: '2'}, {id: 5, name: '4'}]
_.intersectionBy(listOfObjects_1, listOfObjects_2, 'id')
var ids_1 = listOfObjects_1.map(o => o.id)
listOfObjects_2.filter(o => ids_1.includes(o.id))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash intersectionBy | |
array filtering with includes |
Test name | Executions per second |
---|---|
lodash intersectionBy | 852457.6 Ops/sec |
array filtering with includes | 14334470.0 Ops/sec |
Let's break down the provided JSON and explain what is being tested.
Benchmark Definition
The benchmark definition specifies two test cases:
_.intersectionBy(listOfObjects_1, listOfObjects_2, 'id')
: This test case uses the lodash
library to perform an intersection by key on two arrays of objects (listOfObjects_1
and listOfObjects_2
) based on the 'id'
key.var ids_1 = listOfObjects_1.map(o => o.id)\nlistOfObjects_2.filter(o => ids_1.includes(o.id))
: This test case manually implements an array filtering with includes method using JavaScript's built-in map
and filter
functions.Options Compared
The two options being compared are:
lodash
library's intersectionBy
function.map
and filter
functions.Pros and Cons of Each Approach
Lodash intersectionBy
Function:
Pros:
Cons:
lodash
library.Manual Implementation using map
and filter
:
Pros:
Cons:
Library: Lodash
Lodash is a popular JavaScript utility library that provides a wide range of functions for tasks such as array manipulation, object transformation, and functional programming. The intersectionBy
function is designed to find the common elements between two arrays of objects based on a specified key.
Special JS Feature/Syntax: None
There are no special JavaScript features or syntax used in this benchmark that would require additional explanation.
Other Alternatives
If you wanted to implement an intersection by key manually without using lodash
, you could use other libraries like underscore
or implement it yourself using a custom function. Alternatively, you could also consider using other built-in functions like Set
and forEach
to achieve the same result.
It's worth noting that both approaches have their trade-offs in terms of performance, readability, and maintainability. The choice between them ultimately depends on your specific use case, personal preference, and project requirements.