Skip to content

perf(js): replace quadratic BPE merge algorithm with optimal heap-based algorithm#156

Open
uriva wants to merge 1 commit into
dqbd:mainfrom
uriva:fix-js-tiktoken-quadratic-merge
Open

perf(js): replace quadratic BPE merge algorithm with optimal heap-based algorithm#156
uriva wants to merge 1 commit into
dqbd:mainfrom
uriva:fix-js-tiktoken-quadratic-merge

Conversation

@uriva

@uriva uriva commented Jul 5, 2026

Copy link
Copy Markdown

There is a performance bottleneck where the pure JS BPE merge algorithm (bytePairMerge) in js-tiktoken runs in quadratic time O(N^2) in the number of characters for long continuous words without spaces (such as repeating a character 3000 times). This causes severe performance degradation, taking almost 10 seconds for just 3000 characters and hanging test suites / downstream LLM agents under Deno/Node.\n\nThis PR fixes the issue by replacing the O(N^2) implementation with a correct, optimal heap-based O(N log N) algorithm (using duplicate pushing/lazy deletion to handle priority increases), speeding up encoding of pathological strings by over 270x (from 9 seconds to 32ms for 3000 characters). This also closes the loop on previous attempts like PR #101 and fixes decoding/matching errors on non-latin and emoji sequences.

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.

1 participant