perf: intern per-character Nodes in characters()#39
Merged
Conversation
characters() allocated a fresh Node per character. Share one immutable Node per character via a lazy cache (the unbounded analogue of _BYTE_NODES for bytes). Nodes are frozen, so sharing is safe and has no memo/settings dependency. Dedups repeated characters (memory) and lets equal characters compare by identity, so merge's tuple comparisons hit CPython's identity short-circuit (speed) — the same effect #36 gave the utf8 byte layer. On repeated multilingual text with units="characters": ~-36% time, ~-45% peak memory. Output identical; 137 tests pass. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
The
characters()unit function allocated a freshNodefor every character. This mirrors theutf8byte layer before #36 — share one immutableNodeper character instead, via a lazy cache (the unbounded analogue of_BYTE_NODES):Nodes are frozen, so sharing is safe, and unlike cachingNodesSequence/graph builders there's no memo/GraphSettingsdependency (aNodeis just bytes). Wins the same two ways #36 did:merge'snodes[i:i+m] == mergecomparisons hit CPython's per-element identity short-circuit.Output identical, 137 tests pass. Measured on repeated multilingual text with
units="characters"(best of 3):Only affects the
charactersunit path (not the defaultutf8_clusters), so the default BPE benchmark is unchanged — but for codepoint-level tokenization it's a sizable win.🤖 Generated with Claude Code