Skip to content

Specialize TreeWalker with struct key comparers - #31

Open
hadashiA wants to merge 1 commit into
mainfrom
claude/readonly-db-optimization-19c03f
Open

Specialize TreeWalker with struct key comparers#31
hadashiA wants to merge 1 commit into
mainfrom
claude/readonly-db-optimization-19c03f

Conversation

@hadashiA

@hadashiA hadashiA commented Aug 7, 2026

Copy link
Copy Markdown
Owner

Summary

Replaces the central guarded-devirtualization hack (KeyCompare) with value-type generic specialization: TreeWalker is now an abstract non-generic base plus sealed TreeWalker<TComparer> where TComparer : struct, IKeyComparer. Each comparer gets its own runtime instantiation, so every comparison in the B+Tree search loops is a direct, inlinable call — on JIT and on AOT targets (IL2CPP) alike — and SupportsKeyDigest folds to a JIT-time constant, removing the digest branch from the binary search loops.

  • IKeyComparer + struct comparers (Int64KeyComparer, AsciiKeyComparer, Uuidv7KeyComparer on .NET 9+, FallbackKeyComparer, DuplicateKeyComparer) in Internal/KeyComparers.cs. Built-in comparers delegate to the sealed encoding singletons, so comparison logic stays in one place.
  • LeafNodeReader / InternalNodeReader search methods take TComparer instead of IKeyEncoding.
  • All instantiations are spelled out in the TreeWalker.Create factory, so IL2CPP generates them statically. Holders (tables, index queries, iterators) keep referencing the non-generic base — public API is unchanged; virtual dispatch is one call per query instead of one per comparison.
  • Custom/plugin encodings (e.g. Ulid) go through FallbackKeyComparer and perform exactly as before. Non-unique secondary indexes get an inlined composite comparer instead of the previous double dispatch.

Benchmark

ReadBenchmark (Release, solo run, Apple M-series / .NET 10), vs current README numbers:

Method Before After
DryDB_FindByKey 18.35 us 16.42 us
DryDB_FindByKey_RandomKeys 33.75 us 29.95 us
DryDB_FindByKeyAsync 23.23 us 21.34 us

RandomKeys (-11%) is the most reliable signal since it defeats the branch predictor — consistent with removing per-comparison branches. Parallel variants are within their usual noise. All read paths remain allocation-free; 75/75 tests pass on net8.0/net10.0/netstandard2.1.

🤖 Generated with Claude Code

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