<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var first = [Array(100)].map(it => ~~(Math.random() * 1000));
var second = [Array(20)].map(it => ~~(Math.random() * 1000));
const firstSet = new Set(first);
const secondSet = new Set(second);
new Set([firstSet].filter(item => secondSet.has(item)));
_.intersection(first, second)
first.filter(it => second.includes(it))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Javascript Set intersection | |
Lodash intersection | |
Javascript Array intersection |
Test name | Executions per second |
---|---|
Javascript Set intersection | 1102998.9 Ops/sec |
Lodash intersection | 493168.4 Ops/sec |
Javascript Array intersection | 758517.7 Ops/sec |
The benchmark provided compares three different approaches for finding the intersection of two arrays in JavaScript. Specifically, it tests the performance of:
JavaScript Set Intersection:
const secondSet = new Set(second);
new Set([...firstSet].filter(item => secondSet.has(item)));
Lodash Intersection:
_.intersection(first, second);
JavaScript Array Intersection:
first.filter(it => second.includes(it));
Array.prototype.filter()
combined with Array.prototype.includes()
, iterating through first
and checking if each element exists in second
.Performance: When dealing with larger datasets, the choice of method can significantly impact performance. Sets generally offer better performance characteristics for this type of operation due to their optimized look-up times.
Library Usage: Lodash is a popular utility library that provides helpful functions for everyday programming tasks. However, it adds to the bundle size, which is a critical consideration for performance-sensitive applications, especially on the web.
Including Other Libraries: Apart from Lodash, there are other libraries like Underscore.js that also provide similar utility functions for array manipulation.
Native Implementations with ES6: With the advent of ES6, options like the native Map
and Set
have been increasingly favored for set-like manipulations, presenting opportunities for cleaner and potentially faster code compared to traditional array methods.
Custom Implementations: Developers often implement their own custom functions for specific use cases or optimizations based on business logic. This allows for more tailored solutions but requires consideration of edge cases and thorough testing.
In summary, when selecting an approach for finding intersections in arrays, developers should weigh the benefits of performance, readability, and resource usage, especially when working within the constraints of client-side environments like browsers.