Commit fb2a9cd
Fix O(n^2) performance bug in uniqArr; avoid duplicate keyF evaluations (#575)
This PR implements two performance optimizations in `uniqueArr`:
- **Fix an O(n^2) performance bug**:
#564 changed this code to
call `out.result()` on every loop iteration, resulting in copying of an
`O(n)` sized array on each loop iteration. We can avoid this by keeping
a reference to the last output element.
- **Avoid duplicate keyF evaluations**: in the old code, each loop
iteration would repeat the `keyF` evaluation for the last element of the
output array; the new code calls `keyF` exactly once per element by
maintaining a `lastAddedKey` variable during the loop.
- This is similar in spirit to
#245
Claude (Opus 4.5) spotted the O(n^2) bug and designed that part of the
fix. I spotted the duplicate keyF evaluation and suggested this fix
(plus the switch to a `while` loop).
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>1 parent 4ab8288 commit fb2a9cd
1 file changed
Lines changed: 11 additions & 14 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
65 | 65 | | |
66 | 66 | | |
67 | 67 | | |
68 | | - | |
69 | | - | |
70 | | - | |
| 68 | + | |
| 69 | + | |
| 70 | + | |
| 71 | + | |
| 72 | + | |
| 73 | + | |
| 74 | + | |
| 75 | + | |
| 76 | + | |
71 | 77 | | |
72 | | - | |
73 | | - | |
74 | | - | |
75 | | - | |
76 | | - | |
77 | | - | |
78 | | - | |
79 | | - | |
80 | | - | |
81 | | - | |
82 | | - | |
| 78 | + | |
83 | 79 | | |
| 80 | + | |
84 | 81 | | |
85 | 82 | | |
86 | 83 | | |
| |||
0 commit comments