Skip to content

Instantly share code, notes, and snippets.

@lxl66566
Last active October 26, 2024 10:59
Show Gist options
  • Select an option

  • Save lxl66566/4dbc102a72efcd64ecfb7df9d5a62970 to your computer and use it in GitHub Desktop.

Select an option

Save lxl66566/4dbc102a72efcd64ecfb7df9d5a62970 to your computer and use it in GitHub Desktop.
TypeScript partition array into two by condition, performance compare
import { Bench } from "tinybench";
const bench = new Bench({
time: 1000,
});
// This will not change the origin array
function partition<T>(
arr: readonly T[],
predicate: (item: T) => boolean,
): [T[], T[]] {
return arr.reduce(
(acc, item) => {
acc[predicate(item) ? 0 : 1].push(item);
return acc;
},
[[], []] as [T[], T[]],
);
}
// This will consume the origin array
function partitionInPlace<T>(
array: T[],
predicate: (item: T) => boolean,
): [T[], T[]] {
const match: T[] = [];
const nonMatch: T[] = [];
while (array.length > 0) {
const item = array.pop() as T;
if (predicate(item)) {
match.push(item);
} else {
nonMatch.push(item);
}
}
return [match, nonMatch];
}
const a = Array.from({ length: 10000 }, (_, i) => i);
bench
.add("partition by reduce", () => {
const [match, nonMatch] = partition(a, (i) => i % 2 === 0);
})
.add("partition by pop", () => {
const [match, nonMatch] = partitionInPlace(a, (i) => i % 2 === 0);
});
await bench.run();
console.table(bench.table());
// Output:
// ┌───────┬───────────────────────┬───────────┬────────────────────┬──────────┬─────────┐
// │ (idx) │ Task Name │ ops/sec │ Average Time (ns) │ Margin │ Samples │
// ├───────┼───────────────────────┼───────────┼────────────────────┼──────────┼─────────┤
// │ 0 │ "partition by reduce" │ "17,601" │ 56813.90182933754 │ "±0.83%" │ 17602 │
// │ 1 │ "partition by pop" │ "737,664" │ 1355.6304013341596 │ "±0.48%" │ 737665 │
// └───────┴───────────────────────┴───────────┴────────────────────┴──────────┴─────────┘
@lxl66566
Copy link
Author

If each element in Array a is Object, the performance difference will be bigger.

┌───────┬───────────────────────┬───────────┬────────────────────┬──────────┬─────────┐
│ (idx) │ Task Name             │ ops/sec   │ Average Time (ns)  │ Margin   │ Samples │
├───────┼───────────────────────┼───────────┼────────────────────┼──────────┼─────────┤
│     0 │ "partition by reduce" │ "8,015"   │ 124755.72604790462 │ "±0.68%" │ 8016    │
│     1 │ "partition by pop"    │ "756,371" │ 1322.1010004322566 │ "±0.41%" │ 756373  │
└───────┴───────────────────────┴───────────┴────────────────────┴──────────┴─────────┘

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment