-
-
Notifications
You must be signed in to change notification settings - Fork 42
perf(core): optimize sort/reverse permutation from O(n^2) to O(n) #38
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
senrecep
wants to merge
5
commits into
dashersw:main
Choose a base branch
from
senrecep:feat/sort-permutation-on-optimization
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 3 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
f39f76e
perf(core): optimize sort/reverse permutation from O(n^2) to O(n)
senrecep e91ea8b
perf(core): replace shift() with cursor in sort permutation bucket lo…
senrecep e5b99ec
bench(core): add sort/reverse permutation O(n^2) vs O(n) benchmark
senrecep f9e128d
bench(core): improve sort permutation benchmark with statistical rigor
senrecep dfd8694
fix(core): apply cursor-based permutation to active sort/reverse handler
senrecep File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| --- | ||
| "@geajs/core": patch | ||
| --- | ||
|
|
||
| ### @geajs/core (patch) | ||
|
|
||
| - **Sort/reverse permutation O(n) optimization**: Replace O(n^2) nested-loop permutation calculation with a Map-based O(n) index lookup, improving performance on large sorted arrays. |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,7 @@ | ||
| node_modules | ||
| .history | ||
| .omc | ||
| .serena | ||
| .DS_Store | ||
| dist | ||
| dist-profile | ||
|
|
||
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| /** | ||
| * Benchmark: sort/reverse permutation O(n²) → O(n) | ||
| * PR #38: Replace indexOf-in-loop with Map-based bucket lookup | ||
| * | ||
| * Run: npx tsx packages/gea/benchmarks/sort-permutation.bench.ts | ||
| */ | ||
|
|
||
| function heapMB() { | ||
| return process.memoryUsage().heapUsed / 1024 / 1024 | ||
| } | ||
|
|
||
| // ---------- OLD implementation (O(n²)) ---------- | ||
| function computePermutationOld(prev: any[], next: any[]): number[] { | ||
| return next.map((v) => { | ||
| const idx = prev.indexOf(v) | ||
| prev[idx] = undefined // mark consumed | ||
| return idx | ||
| }) | ||
| } | ||
|
|
||
| // ---------- NEW implementation (O(n)) ---------- | ||
| function computePermutationNew(prev: any[], next: any[]): number[] { | ||
| const idxMap = new Map<any, number[]>() | ||
| for (let i = 0; i < prev.length; i++) { | ||
| const a = idxMap.get(prev[i]) | ||
| a ? a.push(i) : idxMap.set(prev[i], [i]) | ||
| } | ||
| const cursors = new Map<any, number>() | ||
| return next.map((v) => { | ||
| const bucket = idxMap.get(v)! | ||
| const cursor = cursors.get(v) ?? 0 | ||
| cursors.set(v, cursor + 1) | ||
| return bucket[cursor] | ||
| }) | ||
| } | ||
|
|
||
| // ---------- Benchmark harness ---------- | ||
| function bench(label: string, fn: () => void, iters: number): number { | ||
| // warm-up | ||
| for (let i = 0; i < 5; i++) fn() | ||
| const t0 = performance.now() | ||
| for (let i = 0; i < iters; i++) fn() | ||
| return performance.now() - t0 | ||
| } | ||
|
|
||
| function makeArray(size: number): number[] { | ||
| return Array.from({ length: size }, (_, i) => i) | ||
| } | ||
|
|
||
| function shuffleArray(arr: number[]): number[] { | ||
| const a = arr.slice() | ||
| for (let i = a.length - 1; i > 0; i--) { | ||
| const j = Math.floor(Math.random() * (i + 1)) | ||
| ;[a[i], a[j]] = [a[j], a[i]] | ||
| } | ||
| return a | ||
| } | ||
|
|
||
| const SIZES = [100, 1000, 5000, 10000] | ||
| const ITERS = 200 | ||
|
|
||
| console.log('\n=== sort/reverse permutation benchmark ===') | ||
| console.log(`${'Size'.padEnd(8)} ${'Old (ms)'.padStart(10)} ${'New (ms)'.padStart(10)} ${'Speedup'.padStart(10)} ${'Heap Δ (MB)'.padStart(12)}`) | ||
| console.log('-'.repeat(56)) | ||
|
|
||
| for (const size of SIZES) { | ||
| const base = makeArray(size) | ||
| const shuffled = shuffleArray(base) | ||
|
|
||
| const h0 = heapMB() | ||
|
|
||
| const oldMs = bench( | ||
| 'old', | ||
| () => { | ||
| const prev = base.slice() | ||
| computePermutationOld(prev, shuffled) | ||
| }, | ||
| ITERS, | ||
| ) | ||
|
|
||
| const h1 = heapMB() | ||
|
|
||
| const newMs = bench( | ||
| 'new', | ||
| () => { | ||
| const prev = base.slice() | ||
| computePermutationNew(prev, shuffled) | ||
| }, | ||
| ITERS, | ||
| ) | ||
|
|
||
| const h2 = heapMB() | ||
| const heapDelta = (h2 - h1).toFixed(3) | ||
| const speedup = (oldMs / newMs).toFixed(1) | ||
|
senrecep marked this conversation as resolved.
Outdated
|
||
|
|
||
| console.log( | ||
| `${String(size).padEnd(8)} ${oldMs.toFixed(2).padStart(10)} ${newMs.toFixed(2).padStart(10)} ${(speedup + 'x').padStart(10)} ${heapDelta.padStart(12)}`, | ||
| ) | ||
| } | ||
|
|
||
| console.log('\nAll sizes: new implementation is O(n) vs O(n²) old.') | ||
| console.log('Speedup scales with array size. Heap delta is minimal.\n') | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add explicit invariant checks in
computePermutationNew.Line 30’s non-null assertion (
!) assumes perfect permutation input. If setup drifts, failure becomes opaque at Line 33. Prefer explicit guards with clear errors.Suggested fix
function computePermutationNew(prev: any[], next: any[]): number[] { const idxMap = new Map<any, number[]>() for (let i = 0; i < prev.length; i++) { const a = idxMap.get(prev[i]) a ? a.push(i) : idxMap.set(prev[i], [i]) } const cursors = new Map<any, number>() return next.map((v) => { - const bucket = idxMap.get(v)! + const bucket = idxMap.get(v) + if (!bucket) throw new Error('Invalid permutation input: value not found in prev') const cursor = cursors.get(v) ?? 0 + if (cursor >= bucket.length) throw new Error('Invalid permutation input: duplicate count mismatch') cursors.set(v, cursor + 1) return bucket[cursor] }) }📝 Committable suggestion
🤖 Prompt for AI Agents