Skip to content

Optimize _sortNodeUp/Down methods and _moveNode method (11x improvement)#664

Merged
ignlg merged 13 commits intoignlg:perf/moveNode-optimizationfrom
ericbstie:perf/moveNode-optimization
Sep 30, 2025
Merged

Optimize _sortNodeUp/Down methods and _moveNode method (11x improvement)#664
ignlg merged 13 commits intoignlg:perf/moveNode-optimizationfrom
ericbstie:perf/moveNode-optimization

Conversation

@ericbstie
Copy link
Contributor

@ericbstie ericbstie commented Apr 27, 2025

Fixes #661. Also fixes #665.

Significantly improves runtime:

image

More details in #661 🚀 🚀 🚀

Summary by CodeRabbit

  • New Features

    • Added documentation for version 2.6, highlighting performance improvements for remove and sorting methods, as well as enhancements to tests and documentation.
  • Documentation

    • Updated documentation pages to reference the new repository and commit links.
    • Added a changelog entry for version 2.6 in the documentation sidebar and main page.
  • Refactor

    • Improved the performance of internal remove and sorting operations in heap structures by optimizing node repositioning logic and simplifying index calculations.

@coderabbitai
Copy link

coderabbitai bot commented Apr 27, 2025

"""

Walkthrough

This update primarily refactors internal methods of the Heap and HeapAsync classes to optimize heap operations. The init method's heapify loop now correctly starts from the last parent node, and the sift-up and sift-down operations have been reimplemented to use a "hole" movement approach rather than swapping nodes at every step. Documentation files were regenerated to reflect a new repository source and commit hash, and the changelog was updated to include version 2.6, highlighting performance improvements and documentation enhancements.

Changes

Files Change Summary
src/Heap.ts, src/HeapAsync.ts Refactored internal heapify, sift-up, and sift-down logic to use a "hole" movement approach rather than swaps; fixed heapify loop to start from last parent node.
docs/functions/toInt.html, docs/types/AsyncComparator.html, docs/types/AsyncIsEqual.html, docs/types/Comparator.html, docs/types/IsEqual.html Updated documentation source links to new repository and commit; no changes to signatures or content.
docs/index.html Updated changelog and sidebar to include version 2.6 with performance and documentation improvements.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Heap
    participant InternalArray

    User->>Heap: init(array)
    Heap->>Heap: for i = lastParent down to 0
    Heap->>Heap:   _sortNodeDown(i)
    Heap->>InternalArray:   Move nodes using "hole" approach (no swaps)
    Heap-->>User: Heap initialized

    User->>Heap: insert(value)
    Heap->>Heap: _sortNodeUp(index)
    Heap->>InternalArray:   Move nodes using "hole" approach (no swaps)
    Heap-->>User: Value inserted
Loading

Assessment against linked issues

Objective Addressed Explanation
Optimize sift-up/sift-down to avoid swapping at every iteration, use "hole" movement (ref #661)
Reduce unnecessary function calls in heap operations (ref #661)
Fix init to only run _sortNodeDown on non-leaf nodes (start at last parent node) (ref #665)

Poem

Oh, what a leap for our heap!
No more swapping in a loop so deep,
Now we move a clever hole,
Making performance our new goal.
Docs refreshed, a changelog treat—
This bunny’s code is fast and neat! 🐇✨
"""


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0789d20 and 877e37f.

⛔ Files ignored due to path filters (2)
  • dist/heap-js.es5.js is excluded by !**/dist/**
  • dist/heap-js.umd.js is excluded by !**/dist/**
📒 Files selected for processing (7)
  • docs/functions/toInt.html (1 hunks)
  • docs/index.html (2 hunks)
  • docs/types/AsyncComparator.html (1 hunks)
  • docs/types/AsyncIsEqual.html (1 hunks)
  • docs/types/Comparator.html (1 hunks)
  • docs/types/IsEqual.html (1 hunks)
  • src/Heap.ts (5 hunks)
✅ Files skipped from review due to trivial changes (1)
  • docs/index.html
🚧 Files skipped from review as they are similar to previous changes (6)
  • docs/functions/toInt.html
  • docs/types/AsyncIsEqual.html
  • docs/types/IsEqual.html
  • docs/types/AsyncComparator.html
  • docs/types/Comparator.html
  • src/Heap.ts
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@ericbstie ericbstie marked this pull request as ready for review April 27, 2025 01:54
@ericbstie
Copy link
Contributor Author

@coderabbitai review

@coderabbitai
Copy link

coderabbitai bot commented Apr 27, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/HeapAsync.ts (1)

730-732: Optimization approach looks good but use const instead of let.

The change from array destructuring to using a temporary variable for swapping elements is a good optimization that will improve performance. This is likely the source of the 11x-22x performance improvement mentioned in the PR title.

However, since temp is never reassigned, you should use const instead of let as per best practices.

- let temp = this.heapArray[j];
+ const temp = this.heapArray[j];
  this.heapArray[j] = this.heapArray[k];
  this.heapArray[k] = temp;
🧰 Tools
🪛 ESLint

[error] 730-730: 'temp' is never reassigned. Use 'const' instead.

(prefer-const)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c6bce4c and 9127d6a.

⛔ Files ignored due to path filters (2)
  • dist/heap-js.es5.js is excluded by !**/dist/**
  • dist/heap-js.umd.js is excluded by !**/dist/**
📒 Files selected for processing (8)
  • docs/functions/toInt.html (1 hunks)
  • docs/index.html (2 hunks)
  • docs/types/AsyncComparator.html (1 hunks)
  • docs/types/AsyncIsEqual.html (1 hunks)
  • docs/types/Comparator.html (1 hunks)
  • docs/types/IsEqual.html (1 hunks)
  • src/Heap.ts (1 hunks)
  • src/HeapAsync.ts (1 hunks)
🧰 Additional context used
🪛 ESLint
src/Heap.ts

[error] 807-807: 'temp' is never reassigned. Use 'const' instead.

(prefer-const)

src/HeapAsync.ts

[error] 730-730: 'temp' is never reassigned. Use 'const' instead.

(prefer-const)

🔇 Additional comments (7)
docs/types/AsyncComparator.html (1)

1-1: Documentation update looks good.

This is just an update to the generated documentation HTML with changes to the source reference URL and commit hash. No functional changes to review.

docs/types/AsyncIsEqual.html (1)

1-1: Documentation update looks good.

This is just an update to the generated documentation HTML with changes to the source reference URL and commit hash. No functional changes to review.

docs/functions/toInt.html (1)

1-2: Documentation source link updated correctly.
The “Defined in” link now points to the BeatsuDev/heap-js repository at commit cc2e4c9b4b1032017a337f59889249bf1a9d27e5. No other content or structure was altered.

docs/types/Comparator.html (1)

1-2: Updated repository and commit hash in source reference.
The “Defined in” link for Comparator now correctly references the new fork and commit. No functional documentation changes detected.

docs/types/IsEqual.html (1)

1-2: Source link adjusted to new commit.
The “Defined in” reference for IsEqual now points to cc2e4c9…/Heap.ts. Content and signature remain unchanged.

docs/index.html (2)

14-17: Changelog entry for version 2.6 inserted correctly.
The new version header and bullet points accurately describe performance improvements and documentation enhancements, placed above the existing 2.5 entry.


171-172: Sidebar navigation updated to include 2.6.
The “On This Page” section now lists the new 2.6 anchor, matching the changelog addition.

@ericbstie ericbstie changed the title Optimize _moveNode method by a factor of 11x - 22x Optimize _moveNode method by a factor of 12x Apr 28, 2025
@ericbstie ericbstie changed the title Optimize _moveNode method by a factor of 12x Optimize _sortNodeUp/Down methods and _moveNode method (11x improvement) Apr 28, 2025
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
src/HeapAsync.ts (3)

434-436: Consider starting heapify at floor(n/2) - 1 to skip the last leaf

Great fix moving the start index from length to length / 2; that eliminates ~50 % of the useless iterations.
You can shave off the final, still-superfluous pass by subtracting one:

-for (let i = Math.floor(this.heapArray.length / 2); i >= 0; --i) {
+for (let i = Math.floor(this.heapArray.length / 2) - 1; i >= 0; --i) {

i = floor(n/2) - 1 is the index of the last parent; anything beyond it is guaranteed to be a leaf and already satisfies the heap property.


741-760: Nice “hole” optimisation; minor micro-optimisation opportunity

The new implementation cuts heap swaps dramatically—👍.
Small tweak: you compute compare(left, right) even when right is out of range; you can avoid one await on the common “single-child” path:

-const best =
-  right >= length || (await this.compare(this.heapArray[left], this.heapArray[right])) < 0
-    ? left
-    : right;
+let best = left;
+if (right < length &&
+    (await this.compare(this.heapArray[left], this.heapArray[right])) > 0) {
+  best = right;
+}

This keeps logic identical while preventing an unnecessary promise allocation when the right child doesn’t exist.


767-778: Mirror optimisation in _sortNodeUp; early‐exit in tight loop

The refactor is correct and clearer; one tiny speed win: check i !== 0 before the await, so we don’t pay the promise cost once we’ve bubbled to the root:

while (i > 0) {
-  const pi = HeapAsync.getParentIndexOf(i);
-  if ((await this.compare(value, this.heapArray[pi])) < 0) {
+  const pi = HeapAsync.getParentIndexOf(i);
+  // If already in place, break early without awaiting next loop
+  if ((await this.compare(value, this.heapArray[pi])) < 0) {

Not a huge deal, but every micro-promise counts inside a tight heap loop.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2894ba5 and 88b3959.

⛔ Files ignored due to path filters (2)
  • dist/heap-js.es5.js is excluded by !**/dist/**
  • dist/heap-js.umd.js is excluded by !**/dist/**
📒 Files selected for processing (11)
  • docs/assets/main.js (1 hunks)
  • docs/assets/style.css (1 hunks)
  • docs/functions/toInt.html (1 hunks)
  • docs/index.html (6 hunks)
  • docs/modules.html (1 hunks)
  • docs/types/AsyncComparator.html (1 hunks)
  • docs/types/AsyncIsEqual.html (1 hunks)
  • docs/types/Comparator.html (1 hunks)
  • docs/types/IsEqual.html (1 hunks)
  • src/Heap.ts (5 hunks)
  • src/HeapAsync.ts (3 hunks)
✅ Files skipped from review due to trivial changes (3)
  • docs/functions/toInt.html
  • docs/modules.html
  • docs/index.html
🚧 Files skipped from review as they are similar to previous changes (5)
  • docs/types/IsEqual.html
  • docs/types/Comparator.html
  • docs/types/AsyncIsEqual.html
  • docs/types/AsyncComparator.html
  • src/Heap.ts
🧰 Additional context used
🪛 Biome (1.9.4)
docs/assets/main.js

[error] 4-4: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 4-4: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 4-4: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 4-4: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 4-4: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 4-4: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 4-4: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 5-5: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 6-6: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 4-4: Shouldn't redeclare 'E'. Consider to delete it or rename it.

'E' is defined here:

(lint/suspicious/noRedeclare)


[error] 4-4: Shouldn't redeclare 'E'. Consider to delete it or rename it.

'E' is defined here:

(lint/suspicious/noRedeclare)


[error] 4-4: Shouldn't redeclare 'E'. Consider to delete it or rename it.

'E' is defined here:

(lint/suspicious/noRedeclare)


[error] 4-4: Shouldn't redeclare 'E'. Consider to delete it or rename it.

'E' is defined here:

(lint/suspicious/noRedeclare)


[error] 4-4: Shouldn't redeclare 'E'. Consider to delete it or rename it.

'E' is defined here:

(lint/suspicious/noRedeclare)


[error] 4-4: Shouldn't redeclare 'E'. Consider to delete it or rename it.

'E' is defined here:

(lint/suspicious/noRedeclare)


[error] 4-4: Shouldn't redeclare 'E'. Consider to delete it or rename it.

'E' is defined here:

(lint/suspicious/noRedeclare)


[error] 4-4: Shouldn't redeclare 'l'. Consider to delete it or rename it.

'l' is defined here:

(lint/suspicious/noRedeclare)


[error] 4-4: Shouldn't redeclare 'c'. Consider to delete it or rename it.

'c' is defined here:

(lint/suspicious/noRedeclare)


[error] 4-4: Shouldn't redeclare 'i'. Consider to delete it or rename it.

'i' is defined here:

(lint/suspicious/noRedeclare)


[error] 4-4: Shouldn't redeclare 'l'. Consider to delete it or rename it.

'l' is defined here:

(lint/suspicious/noRedeclare)


[error] 4-4: Shouldn't redeclare 'f'. Consider to delete it or rename it.

'f' is defined here:

(lint/suspicious/noRedeclare)


[error] 4-4: Shouldn't redeclare 'y'. Consider to delete it or rename it.

'y' is defined here:

(lint/suspicious/noRedeclare)


[error] 4-4: Shouldn't redeclare 'f'. Consider to delete it or rename it.

'f' is defined here:

(lint/suspicious/noRedeclare)


[error] 4-4: Shouldn't redeclare 'y'. Consider to delete it or rename it.

'y' is defined here:

(lint/suspicious/noRedeclare)


[error] 4-4: Shouldn't redeclare 'l'. Consider to delete it or rename it.

'l' is defined here:

(lint/suspicious/noRedeclare)


[error] 4-4: Shouldn't redeclare 'y'. Consider to delete it or rename it.

'y' is defined here:

(lint/suspicious/noRedeclare)


[error] 4-4: Shouldn't redeclare 'l'. Consider to delete it or rename it.

'l' is defined here:

(lint/suspicious/noRedeclare)


[error] 4-4: Shouldn't redeclare 'Q'. Consider to delete it or rename it.

'Q' is defined here:

(lint/suspicious/noRedeclare)


[error] 4-4: Shouldn't redeclare 'l'. Consider to delete it or rename it.

'l' is defined here:

(lint/suspicious/noRedeclare)


[error] 4-4: Shouldn't redeclare 'T'. Consider to delete it or rename it.

'T' is defined here:

(lint/suspicious/noRedeclare)


[error] 4-4: Shouldn't redeclare 'c'. Consider to delete it or rename it.

'c' is defined here:

(lint/suspicious/noRedeclare)


[error] 4-4: Shouldn't redeclare 'd'. Consider to delete it or rename it.

'd' is defined here:

(lint/suspicious/noRedeclare)


[error] 4-4: Shouldn't redeclare 's'. Consider to delete it or rename it.

's' is defined here:

(lint/suspicious/noRedeclare)


[error] 4-4: Shouldn't redeclare 'r'. Consider to delete it or rename it.

'r' is defined here:

(lint/suspicious/noRedeclare)


[error] 4-4: Shouldn't redeclare 'r'. Consider to delete it or rename it.

'r' is defined here:

(lint/suspicious/noRedeclare)


[error] 4-4: Shouldn't redeclare 'i'. Consider to delete it or rename it.

'i' is defined here:

(lint/suspicious/noRedeclare)


[error] 4-4: Shouldn't redeclare 'i'. Consider to delete it or rename it.

'i' is defined here:

(lint/suspicious/noRedeclare)


[error] 4-4: Shouldn't redeclare 'i'. Consider to delete it or rename it.

'i' is defined here:

(lint/suspicious/noRedeclare)


[error] 4-4: Shouldn't redeclare 'i'. Consider to delete it or rename it.

'i' is defined here:

(lint/suspicious/noRedeclare)


[error] 4-4: Use a regular expression literal instead of the RegExp constructor.

Regular expression literals avoid some escaping required in a string literal, and are easier to analyze statically.
Safe fix: Use a literal notation instead.

(lint/complexity/useRegexLiterals)

🔇 Additional comments (3)
docs/assets/style.css (2)

994-996: Skip: No functional impact from comment reformatting
The conversion to a multi-line, asterisk-prefixed comment is purely stylistic and doesn’t alter any behavior. No further action needed.


1001-1002: Approve: Accordion arrow now rotates for h5 headings
Extending the selector to target h5 > svg:first-child ensures closed accordions with <h5> summaries also display the rotated arrow. Well aligned with the existing patterns.

docs/assets/main.js (1)

2-2: Approve: Expanded translation mappings for all code entity kinds
The window.translations object now covers all numeric kind_* identifiers from TypeDoc, matching their human-readable labels. No issues spotted.

Comment on lines 729 to 733
_moveNode(j: number, k: number): void {
[this.heapArray[j], this.heapArray[k]] = [this.heapArray[k], this.heapArray[j]];
const temp = this.heapArray[j];
this.heapArray[j] = this.heapArray[k];
this.heapArray[k] = temp;
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

_moveNode is now dead code – delete it to avoid maintenance overhead

After the refactor, neither _sortNodeDown nor _sortNodeUp call _moveNode, and a quick scan shows no other usages. Keeping an unused helper invites confusion and bloats the bundle.

-  _moveNode(j: number, k: number): void {
-    const temp = this.heapArray[j];
-    this.heapArray[j] = this.heapArray[k];
-    this.heapArray[k] = temp;
-  }
+  // _moveNode   <-- remove entire method (no callers left)

Run this to confirm zero references:


🏁 Script executed:

#!/bin/bash
rg --line-number "_moveNode\(" | grep -v "function _moveNode"

Length of output: 683


Tests reference _moveNode—update tests or retain the method before deleting

The _moveNode helper is exercised by your private‐methods tests, so removing it outright will break those specs. You have two options:

• Remove or refactor these tests to use the public API (e.g., swap nodes by calling _sortNodeUp/_sortNodeDown indirectly)
• Keep _moveNode (and its declarations in HeapAsync/Heap and the .d.ts files) until the tests no longer depend on it

Affected locations:

  • src/HeapAsync.ts (lines 729–733)
  • src/Heap.ts (around line 805)
  • tests/heap/heap-private-methods.test.ts (lines 32–37)
  • tests/heap-async/heap-async-private-methods.test.ts (lines 41–46)
  • dist/types/HeapAsync.d.ts
  • dist/types/Heap.d.ts

Committable suggestion skipped: line range outside the PR's diff.

@ericbstie
Copy link
Contributor Author

The _moveNode method is now obsolete (not used anywhere), but it might be good to keep it for a while in case some users of the library for some reason use that method 🤷🏻‍♂️

3 improvements to the sortNodeUp/Down were made incrementally in this PR:

  1. Use temp variable instead of destructure syntax (this one is later superseded by improvement 3)
  2. Use bitshift to calculate parentIndex instead of Math.floor
  3. Move only one node during the sortingUp/Down, then insert the value at the correct place at the end (move hole instead of swapping nodes)
    image

Comparison without baseline:

image

Other

The implementation of the improvements above relied on #665 (start sortNodeDown at length/2, not length in init ) being fixed for the tests to pass.

Script used for visualizations above:

import { lineplot, bench, compact, run } from "mitata";


import { Heap as BaselineHeap } from "heap-js";
import { Heap as MoveNodeImprovedHeap } from "./heap-temp.umd"
import { Heap as BitshiftParentIndexHeap } from "./heap-bitshift.umd"
import { Heap as HoleHeap } from "./heap-hole.umd"


compact(() => {
    lineplot(() => {
        bench("Optimize _moveNode method (no destructure syntax)", function*(ctx: any) {
            yield () => {
                const heap = new MoveNodeImprovedHeap();
                for (let i = ctx.get("size") - 1; i >= 0; i--) { heap.push(i) }
                for (let i = ctx.get("size") - 1; i >= 0; i--) { heap.pop() }
            }
        }).dense_range("size", 100, 50_000, 1_000)
        bench("Use bitshift for parent index", function*(ctx: any) {
            yield () => {
                const heap = new BitshiftParentIndexHeap();
                for (let i = ctx.get("size") - 1; i >= 0; i--) { heap.push(i) }
                for (let i = ctx.get("size") - 1; i >= 0; i--) { heap.pop() }
            }
        }).dense_range("size", 100, 50_000, 1_000)
        bench("Move hole instead of swapping nodes", function*(ctx: any) {
            yield () => {
                const heap = new HoleHeap();
                for (let i = ctx.get("size") - 1; i >= 0; i--) { heap.push(i) }
                for (let i = ctx.get("size") - 1; i >= 0; i--) { heap.pop() }
            }
        }).dense_range("size", 100, 50_000, 1_000)
    })
})

await run();

@CarlOlson
Copy link

@ignlg Is this able to be merged? The tests pass locally (not sure why CI failed, but the log expired).

If this merges, then this library will be competitive with the fastest implementations. And due to the clean code, good testing, and full API, it would be the preferred implementation by a large margin!

@ignlg
Copy link
Owner

ignlg commented Sep 30, 2025

This PR must point to next branch to create a pre-release first. I will do it as soon as possible and push this forward.

@ignlg ignlg changed the base branch from master to next September 30, 2025 08:36
@ignlg ignlg changed the base branch from next to perf/moveNode-optimization September 30, 2025 08:56
@ignlg ignlg merged commit 17e1ec5 into ignlg:perf/moveNode-optimization Sep 30, 2025
5 of 7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

init function unnecessarily runs _sortNodeDown on all nodes Heap-js is 11x - 22x slower than heap

3 participants

Comments