Last active
October 26, 2024 10:59
-
-
Save lxl66566/4dbc102a72efcd64ecfb7df9d5a62970 to your computer and use it in GitHub Desktop.
TypeScript partition array into two by condition, performance compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 │ | |
| // └───────┴───────────────────────┴───────────┴────────────────────┴──────────┴─────────┘ |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If each element in Array a is Object, the performance difference will be bigger.