Skip to content

Instantly share code, notes, and snippets.

@jwickens
Last active August 18, 2025 09:40
Show Gist options
  • Select an option

  • Save jwickens/d2e07bd42a172f3dcef5dbd5596c2194 to your computer and use it in GitHub Desktop.

Select an option

Save jwickens/d2e07bd42a172f3dcef5dbd5596c2194 to your computer and use it in GitHub Desktop.
Lodash _.intersection vs Native Set.intersection
const _ = require("lodash");
// Generate test data
const size = 100000;
const arr1 = Array.from({ length: size }, (_, i) => i);
const arr2 = Array.from({ length: size }, (_, i) => i + size / 2);
// Benchmark helper
function benchmark(label, fn, iterations = 10) {
const start = process.hrtime.bigint();
for (let i = 0; i < iterations; i++) {
fn();
}
const end = process.hrtime.bigint();
const ms = Number(end - start) / 1e6;
console.log(`${label}: ${(ms / iterations).toFixed(3)} ms avg`);
}
// Using ES6 Set
function setIntersection(a, b) {
const setB = new Set(b);
return [...new Set(a)].filter(x => setB.has(x));
}
// Run benchmarks
benchmark("Lodash _.intersection", () => _.intersection(arr1, arr2));
benchmark("Native Set.intersection", () => setIntersection(arr1, arr2));
➜ api git:(discounts-clean-new) ✗ node 'bench_intersection.js'
Lodash _.intersection: 0.134 ms avg
Native Set.intersection: 0.011 ms avg
➜ api git:(discounts-clean-new) ✗ node 'bench_intersection.js'
Lodash _.intersection: 0.132 ms avg
Native Set.intersection: 0.010 ms avg
➜ api git:(discounts-clean-new) ✗ node 'bench_intersection.js'
Lodash _.intersection: 0.134 ms avg
Native Set.intersection: 0.010 ms avg
➜ api git:(discounts-clean-new) ✗ python
Python 3.11.9 (main, May 3 2024, 21:35:31) [Clang 15.0.0 (clang-1500.0.40.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> (0.010 - 0.134)/0.134
-0.9253731343283582
>>>
➜ api git:(discounts-clean-new) ✗ node 'bench_intersection.js'
Lodash _.intersection: 15.748 ms avg
Native Set.intersection: 11.197 ms avg
➜ api git:(discounts-clean-new) ✗ node 'bench_intersection.js'
Lodash _.intersection: 15.813 ms avg
Native Set.intersection: 11.149 ms avg
➜ api git:(discounts-clean-new) ✗ node 'bench_intersection.js'
Lodash _.intersection: 15.749 ms avg
Native Set.intersection: 11.065 ms avg
➜ api git:(discounts-clean-new) ✗ python
Python 3.11.9 (main, May 3 2024, 21:35:31) [Clang 15.0.0 (clang-1500.0.40.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> (15 - 11)/15
0.26666666666666666
>>>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment