Search, illustrated

A VISUAL GUIDE TO SortedArrayIndex.cs

How a string becomes
a search result.

Start with GB19, US12, and US99. See how this class arranges them, finds them, and keeps searching while the collection changes.

Start with three strings
Starts with "US"
0GB19
1 · startUS12
2US99
3
end

Arrange once. Find the edges. Return the block.

Part 2 of Search, illustrated · Play / pause and step controls · Exact string examples

01

One collection, three ways to arrange it

We have these three unique strings: GB19, US12, US99. A plain scan would check each string for every request. This class does extra work up front so that each kind of search can jump to a smaller part of the data.

An index here is an arranged view of those strings. Think of three lists that answer three different questions:

STARTS WITH

"US" → US12, US99

Sort by reading from the left.

GB19US12US99

ByPrefix: the US strings sit together.

ENDS WITH

"9" → GB19, US99

Sort by reading from the right.

US12GB19US99

BySuffix: strings ending in 9 sit together.

CONTAINS

"9" → GB19, US99

Arrange the text starting at each position.

9 GB199 US9999 US99

Substrings: find the block, then remove repeated hits.

One rule makes all three work. In the right arrangement, all the matches are neighbors. We only need to find where that group starts and ends.

What does “sorted” mean for these strings?

Comparisons are ordinal and case-sensitive: compare the numeric UTF-16 values of the characters, without language-specific alphabet rules. "US12" comes before "US99" because, after the shared US, '1' is smaller than '9'. "us12" does not start with "US". There is no case folding or Unicode normalization.

Strings stand in for entries. The index really stores Entry(Key, Id): queries match the Key, and the caller gets the Id back to find its entity. Two entries may share a Key (two companies with one name); they then sort by Id. This page shows only the Keys, because every decision below is made on them.

The constructor first puts the input into a HashSet<Entry>. If we pass ["US99", "GB19", "US99", "US12"], the repeated US99 disappears. We index three unique strings.

02

Build the views, with actual text

Build creates two arrays of references to the original strings, plus an array describing starting positions inside them. The three construction tasks run concurrently through Parallel.Invoke.

The ending view reads right to left

For US12, read 2 → 1 → S → U. For GB19, read 9 → 1 → B → G. For US99, read 9 → 9 → S → U.

How SuffixOrder arranges the original strings
Original stringRead from the endWhy it is here
US122 1 S ULast character 2 comes before 9.
GB199 1 B GTied on the last 9; next character 1 comes before 9.
US999 9 S UFollows GB19 after comparing the next character.

Now every string ending in "9" is in one block: [GB19, US99]. To search for "19", read the query from the right too: first 9, then 1. Only GB19 matches. The code compares backward; it does not allocate reversed strings.

The inside view starts at every character

To find "S9" inside US99, make the text at position 1 searchable. The same idea applies at every position:

0U
1S
29
39
Four entries from one string, US99
Stored entryText used for sortingWhat it can find
(US99, 0)US99Fragments starting at U, such as "US".
(US99, 1)S99Fragments starting at S, such as "S9".
(US99, 2)99"9" or "99".
(US99, 3)9"9" again. We will handle this duplicate shortly.

The struct is called Substring, but it stores (Item, Offset, Repeat): not a copy of the text, and not even the string. Item is the string’s position in ByPrefix: GB19 is 0, US12 is 1, US99 is 2. US99 from position 2 is stored as (2, 2); the sorting code reads ByPrefix[2], which is US99, from position 2 and sees "99". A four-character string contributes four entries; our three strings contribute twelve. These are all starting positions, not every possible start/end pair. The page writes an entry as (US99, 2) where the string is easier to follow.

Why a number instead of the string? An entry is 8 bytes and holds no reference, so the garbage collector never has to look inside the array. When entries held the string (16 bytes), every merge at 1,000,000 ISINs produced a fresh array of 12 million references, and the next collection scanned all of them: a pause of about 26 ms after every merge. The price is one more array read whenever an entry is compared or returned.
WATCH THE BUILD

From three strings to twelve entries

SortedSubstrings
Why count first, then sort the buckets?

Imagine putting entries into trays labeled by their first character. The '9' tray gets "9" from GB19, "99" from US99, and "9" from US99. A '1' tray gets "19" and "12". Entries beginning with 1 must come before entries beginning with 9, regardless of the remaining characters.

  1. Count. start[c + 1]++ counts how many entries begin with character c. For '9', the count is 3.
  2. Add the counts cumulatively. There are three entries before the '9' tray: "12", "19", "2". So start['9'] = 3, start['9' + 1] = 6. Its reserved slice is [3, 6).
  3. Fill. next starts as a copy of start. Each '9' entry occupies the next free position in that tray; incrementing next['9'] moves its cursor.
  4. Sort each tray. "9" precedes "99" because the shorter text runs out first. Equal text is ordered by the original Key, then Id: GB19 before US99. Trays with one entry need no sort.
  5. Fill Repeat. After sorting, calculate the duplicate information for each entry in parallel. Repeat does not affect sorting.
  6. Renumber. The three sorts run at once, so ByPrefix is not sorted yet while the entries are made: they first number strings by input order. Sorting ByPrefix also records where each string went, and one parallel pass rewrites every Item to its string’s ByPrefix position. The order of entries does not change, because ties compare the strings, not their numbers.

This is a counting-sort step followed by comparison sorts inside buckets. There are 65,536 possible UTF-16 code units; the start array has 65,537 slots so even the last bucket has an end position. Larger buckets are scheduled first, with NoBuffering, to avoid leaving a big sort until other workers are idle. The final arrangement is the same whichever worker finishes first.

Current constructor limitation: [] or only empty strings

The search rules can handle an empty view, and an empty string can be indexed alongside nonempty strings. However, constructing this version with [] or [""] throws: SortedSubstrings eventually calls Partitioner.Create(0, 0), which requires a nonempty range. At least one initial string must contain a UTF-16 code unit. This is an existing implementation limitation, not a requirement of binary search. Removing all strings after a successful construction can still produce an empty logical collection.

03

Find the two edges of "US"

In [GB19, US12, US99], the matching strings start at position 1 and stop just before position 3. We write this as [1, 3): include 1, exclude 3. The count is 3 − 1 = 2. Position 3 is a gap after the array, not another item.

0 · beforeGB19
1 · startUS12
2 · matchUS99
3end →

FindBlock returns ArraySegment(ByPrefix, 1, 2): a window onto those two array entries.

Binary search checks the middle of the remaining range. Because the strings are arranged, a comparison tells us which whole side cannot contain the edge. We discard that side and repeat. We do this twice: once for the start, once for the end.

When comparing against "US", GB19 is before the block, while both US12 and US99 count as matching. We compare just enough characters for the query. We are looking for the edges of a group, rather than stopping at the first match.

TRY THE TWO SEARCHES

Watch the possible range shrink

FindBlock · Boundary
Examples:
still possiblemiddle being testedmatching block / resultDimmed = outside this search range

Contains also has a finishing step to remove duplicate entries. This simulator uses the same UTF-16 ordering and boundary rules as the C# class; it runs locally in JavaScript.

Why the unusual ~BinarySearch(...)?

The code supplies a pretend Boundary value. The start boundary sorts just before all matches; the end boundary sorts just after all matches. It always compares as +1 or −1, never 0, so BinarySearch always reports “not found.” The useful part is where that boundary would be inserted.

Start boundary belongs at 1BinarySearch returns −2~(−2) gives 1

The ~ operator is a bitwise complement. .NET encodes an unsuccessful search as ~insertionPosition; applying ~ again recovers the position. For the end, the code searches only the slice starting at start, then adds start back. Here the local end position is 2, so the absolute end is 1 + 2 = 3.

With "FR", the insertion position for both edges is 0: [0, 0), an empty result. With "ZZ", both are 3: [3, 3). With "", all strings match, even an empty string.

Compare for sorting versus compare for matching

PrefixOrder.Compare("US12", "US99") is negative: it must distinguish two items for sorting. PrefixOrder.CompareToQuery("US12", "US") and CompareToQuery("US99", "US") are both 0: they belong to the same query block.

Boundary.CompareTo reverses that item-versus-query relationship because .NET is asking how the boundary compares to the item. The start boundary goes left on a match; the end boundary goes right. IOrder<T> lets the same FindBlock machinery use the prefix, suffix, or substring comparison rule. These are struct comparers; the generic implementation allows specialized comparisons without a separate search implementation for every view. PrefixOrder and SuffixOrder carry nothing; SubstringOrder carries ByPrefix, because its entries hold item numbers and it must read the strings they name.

A short item behaves correctly too: "U" comes before a search for "US", because the item runs out before the query is fully matched.

04

"US99" contains "9" twice. Return it once.

Searching inside a string becomes a starts-with search on its starting positions. US99.Contains("S9") is true because the entry (US99, 1) has text "S99", which starts with "S9".

For Filter("9"), the sorted entries are:

The complete Substrings array for GB19, US12, US99
PositionText being comparedStored (Item, Offset) · its stringRepeat
012(1, 2) US120
119(0, 2) GB190
22(1, 3) US120
3 · start9(0, 3) GB190 → keep
49(2, 3) US991 → skip for "9"
599(2, 2) US990 → keep
6 · endB19(0, 1) GB190
7GB19(0, 0) GB190
8S12(1, 1) US120
9S99(2, 1) US990
10US12(1, 0) US120
11US99(2, 0) US990

Every row reads its string through ByPrefix[Item], to compare its text and, for a hit, to return the Entry: a kept (0, 3) returns ByPrefix[0], GB19.

FindBlock gives [3, 6): three matching entries, but only two unique strings. Here is how RepeatAt makes that easy to fix without building a new set for every query.

EARLIER POSITION 2
US99

Text: "99"

LATER POSITION 3
US99

Text: "9"

The text at position 3, "9", shares one starting character with the text at position 2, "99". No earlier position shares more. So RepeatAt("US99", 3) = 1.

Keep a matching entry only when fragment.Length > Repeat.
For "9": length 1 is not greater than Repeat 1, so skip position 3. Position 2 has Repeat 0, so keep it. We return US99 once.

This number is calculated within the same original string, not by comparing neighboring entries in the sorted array. That matters: the two entries with text "9" belonging to different strings must both remain eligible.

TRY REPEATED TEXT

Which occurrence gets to represent the string?

RepeatAt · Filter
Examples:

For "AAAA", the entries starting at offsets 0, 1, 2, 3 have Repeat values 0, 3, 2, 1. With "AA", offsets 0, 1, and 2 match. Only offset 0 passes 2 > Repeat. The first occurrence represents the string, even when occurrences overlap.

What if US99 was removed or FR99 was just added?

  1. Find base hits. For "9", get GB19 at offset 3, US99 at offset 3, and US99 at offset 2.
  2. Locate the removed string’s representative. If US99 is in Removed, US99.IndexOf("9") gives 2, and a binary search of ByPrefix gives its number, also 2. Binary-search (2, 2) within the matching block: its block-relative position is 2. Save that in removedAt.
  3. Check pending additions directly. FR99.Contains("9") is true, so keep FR99 in a list of its own. Added strings are never in Base, so they cannot repeat a base hit.
  4. Walk the block, once a hit is read. Keep GB19, read from ByPrefix[0]. Skip the later occurrence of US99 using Repeat. Skip its first occurrence because its position is in removedAt. Sorting removedAt lets one cursor follow all removals. Then append FR99. Result: [GB19, FR99].

The small Added and Removed collections have prefix and suffix arrays, but no substring index. For contains searches, the code uses IndexOf on removals and Contains on additions. This keeps each write from copying a substring index for the pending changes.

The walk waits until a hit is read

Steps 1–3 run inside Filter. It then returns a Hits object holding the block, removedAt and the matching additions. Step 4 runs only when the caller reads a hit, and only as far as it reads:

  1. Count reads only Repeat values. Entries passing 1 > Repeat, minus removals, plus additions: 2 − 1 + 1 = 2. No string is read, and neither is ByPrefix. Subtracting removals is safe because each removed representative is its string’s first occurrence, so it always passes the Repeat check.
  2. The first read finds 16 hits, or all of them when there are fewer. The result remembers where its walk stopped in the block and in removedAt.
  3. A read past those 16 finds all the rest in one go, continuing from where the walk stopped.

Why wait? At 1,000,000 ISINs a one-letter fragment’s block holds hundreds of thousands of entries, and a search box reads the count and ten hits. Building every hit up front cost about 22 MB per keystroke. Growing in steps (16, 32, 64, …) re-copies what was already found: a caller reading every hit was about 1.5× slower than with the plain list. Jumping from 16 straight to all of them costs what the plain list did.

A result read long after Filter returned still shows the State that Filter read: the block, ByPrefix, removedAt and the additions never change (see chapter 07). The price is that a result kept alive also keeps that Snapshot’s ByPrefix and Substrings arrays alive.

The empty fragment is special. Every string contains "", including "" itself. An empty string has zero starting-position entries. Therefore Filter("") delegates to GetByStartsWith(""), which includes it.

05

Add "FR77" without rebuilding everything

Inserting into a large sorted array can move many entries. Instead, keep the large arrays unchanged and collect small pending changes beside them. State holds these three pieces:

BASEGB19 · US12 · US99

The last built arrays.

ADDEDFR77

New strings absent from Base.

REMOVEDUS12

Strings still in Base, hidden from searches.

The logical collection is now [FR77, GB19, US99]. The Base arrays still physically contain US12. A search consults the pending changes, so it already sees the current collection.

CHANGE THE COLLECTION

Try a write, then search immediately

Add · Remove · WithDelta
Try:

Show both sorted views of Added and Removed

This small lab uses the actual threshold rule. It limits input lengths and pending changes to keep diagrams readable; normal C# inputs have no such UI limits.

Four writes that cancel each other

Start with Base = [GB19, US12, US99], Added = [], Removed = []
OperationAdded afterwardRemoved afterwardWhy
Add("FR77")[FR77][]FR77 is new; leave Base alone.
Remove("FR77")[][]Cancel its pending addition. Base never had it.
Remove("US12")[][US12]Hide the string still present in Base.
Add("US12")[][]Cancel its pending removal. Base still has it.

_items is the writer’s set of all currently present strings. It makes Add("US99") a no-op when US99 is already present, and Remove("ZZ00") a no-op when ZZ00 is absent. Searches use State rather than reading this mutable set.

Delta.With and Delta.Without make new prefix and suffix arrays. To insert FR77 into prefix order [GB19, US55], binary search gives insertion position 0, then the code copies [] + [FR77] + [GB19, US55]. Removing GB19 finds its position and copies the pieces on either side. The old delta arrays stay unchanged.

A prefix search with pending changes

Suppose Added is [US55] and Removed is [US12]. WithDelta finds the "US" block separately in Base, Removed, and Added:

Base: US12, US99−Removed: US12+Added: US55=US55, US99

A query for "GB" has no matching additions or removals, so the code returns the Base window [GB19] directly, without copying its entries. The ends-with path does the same thing using the suffix-sorted views.

06

Copy stretches. Insert US55. Skip US12.

Both query-time overlays and full merges use MergeSorted. It builds a plan of positions first. It does not sort the whole Base again.

Use Base [GB19, US12, US99], Removed [US12], and Added [US55]. Binary search locates US12 at position 1. US55 would be inserted at position 2, before US99. Those positions refer to the original input array, before any removal changes a position.

FOLLOW THE COPY

A new array from a plan of positions

MergeSorted · Merged.Copy

In Merged.Copy, from tracks the next unread position in the original array, to tracks the next free output position, and r / a track removal / addition events. Copy all unchanged entries before the next event in one span operation. Then either write the added item or advance past the removed one. Finish by copying the remaining tail.

When an insertion and removal share a position, insertion goes first. For example, Base [GB19, US12], Removed [GB19], Added [FR77]: FR77’s insertion gap and GB19’s removal are both at position 0. Write FR77, skip GB19, then copy US12. Result: [FR77, US12].

Knowing the count does not require copying the result

Merged<T> is a result that initially holds the plan. Its Count is just baseCount − removedCount + addedCount. For the "US" query above, that is 2 − 1 + 1 = 2. Reading Count does not build the combined result array.

Accessing an element or enumerating the result calls ToArray(), which copies the entire combined result and caches it. Asking for only the first item still triggers that copy. Concurrent readers may both create a copy; both contain the same values. Filter’s result goes further: its first read finds only 16 hits (see chapter 04).

When does the whole Base get replaced?

Publish merges when Added.Count + Removed.Count reaches max(256, _items.Count / 128), using integer division. The count is of pending items, not every write call. Add FR77 and immediately remove it: the pending count returns to zero.

Threshold examples, using the current live item count after the write
Live unique stringsCount / 128, rounded downMerge at this many pending items
30256
100,000781781
1,000,0007,8127,812

At the threshold, Merge constructs new prefix, suffix, and substring arrays. For prefix and suffix it uses their already-sorted deltas. For substrings it generates every removed and added starting-position entry with SubstringsOf. It sorts the new entries; removed entries need no sort because their located positions are sorted instead. After copying, the new State has empty Added and Removed collections.

Substring entries are renumbered while they are copied

Substring entries name strings by their ByPrefix position, and the merge moves those positions. US55’s entries are made before US55 has a place, so they are numbered 3, one past the old ByPrefix: SubstringOrder reads numbers below 3 from the old ByPrefix and 3 onward from Added. Merged.NewIndexes turns the ByPrefix plan into a table from each old number to its new one:

Old ByPrefix [GB19, US12, US99] plus US55, minus US12 → new ByPrefix [GB19, US55, US99]
Old numberStringNew number
0GB190
1US12removed (−1)
2US992
3 · addedUS551

The substring copy passes every entry through that table: US99’s (2, 2) stays (2, 2), US55’s (3, 0) becomes (1, 0), and US12’s entries are skipped. That is one table read per entry instead of a plain block copy, done on all cores. It is what keeps the array free of references (see chapter 02).

Why wait? Replacing a large Base copies a lot of entries. Batching changes spreads that cost across writes. Larger collections get a larger threshold to reduce how often their large arrays are copied. Waiting too long costs too: every ordinary write copies the delta, so a larger delta makes each write slower, and searches under writes check more pending items. The divisor 128 measured fastest for updates; with 64 merges come twice as often, and with 256 or more each write copies a longer delta. The merge runs synchronously in the triggering writer while it holds the write lock; it is not a background task.

07

A reader can finish with the old view

Imagine Reader A searches for "US" just before a writer removes US12. Reader A may keep [US12, US99]. A later search must see [US99]. Changing the old array in place would make Reader A’s result unstable.

STEP THROUGH THE HANDOFF

One published State per search

Volatile.Read · Volatile.Write
  1. Reader A takes one reference. Volatile.Read(ref _state) gives it the old State. Its Base, Added, and Removed all come from that same State.
  2. The writer prepares a replacement. Under _writeLock, it changes _items and creates a State with US12 in Removed. The old State and arrays remain unchanged.
  3. Publish swaps the reference. Volatile.Write publishes the complete new State. No search sees a half-updated combination of arrays.
  4. Reader B starts after Remove returns. It sees the newly published State and filters out US12. Reader A can still finish against its old State.

Writers are serialized by the lock. Searches do not take that lock and can continue using the old State while a writer builds a merge. An earlier result can outlive a later merge because its arrays are still referenced; the garbage collector can reclaim them when nobody holds them.

The guarantee is one consistent State per individual search. Three successive calls are three reads and may see different writes between them. Existing results are snapshots, not live lists that update after every write.

What “unchanged arrays” means at the API boundary

The implementation never mutates published arrays and returns IReadOnlyList<string>. That is a read-only API contract, not a tamper-proof container: an unmodified Base window is an ArraySegment<string>, whose backing array can be recovered by a caller that deliberately downcasts. Treat returned results as read-only. The snapshot explanation assumes callers honor that contract.

08

Follow a whole request, end to end

Start with [GB19, US12, US99]. Call Remove("US99"), then Add("FR99"), then Filter("9"). Here is every stage working together:

1

Write the pending changes

Base stays [GB19, US12, US99]. Removed becomes [US99]. Added becomes [FR99]. Each write publishes a new State; two pending items are below the merge threshold.

Add / Remove → Delta.With → Publish
2

Read a consistent view

Filter takes one State reference. It will use that State’s Base and both deltas even if another writer publishes a newer State.

Volatile.Read(ref _state)
3

Find the "9" block

Two boundary searches return [3, 6): "9" from GB19 at 3, "9" from US99 at 3, and "99" from US99 at 2.

FindBlock<Substring, SubstringOrder>
4

Find the removal’s first occurrence

US99.IndexOf("9") gives 2, and US99 is number 2 in ByPrefix. Search for (2, 2) inside the block; its relative position is 2. The tie-breaker on the original item keeps different strings’ entries distinguishable.

IndexOf → BinarySearch → removedAt.Sort
5

Include the pending addition

FR99.Contains("9") is true, so FR99 joins the additions. Filter returns a Hits result: Count is 2 kept − 1 removed + 1 added = 2, from Repeat values alone. No hit has been found yet.

Added.ByPrefix → Contains → new Hits(...)
6

Find hits when they are read

Reading the first hit walks the block. GB19 passes 1 > Repeat 0. US99 at offset 3 fails 1 > Repeat 1. US99 at offset 2 is explicitly removed. Then FR99 is appended. The result is [GB19, FR99]; no Base merge was needed.

Hits indexer → FindUpTo
Result order is not part of the interface contract. Prefix and suffix results follow their respective view order. Contains walks substring order, then appends matching additions in prefix order; its output is not guaranteed to be alphabetically sorted. If your caller needs a particular order, it must sort the result.

What work did we save, and what did we pay for?

With a million short strings, locating a prefix edge takes roughly twenty middle checks rather than inspecting a million items. We locate two edges. Comparing each entry still takes character work, and returning a million matching strings still means reading a million results.

Costs in terms of the concrete work performed
OperationWork performedTradeoff
BuildSort two string views; create one entry per UTF-16 code unit, bucket and sort entries, calculate Repeat, renumber to ByPrefix positions.More startup work and memory for faster repeated searches. A 12-unit string contributes 12 substring structs of 8 bytes.
Starts / endsTwo binary searches per relevant view (Base, Removed, Added), then locate delta changes if any.An unchanged matching block can be returned without copying. A changed block is copied in full when enumerated or indexed.
ContainsTwo boundary searches, inspect pending additions/removals. Count scans the block’s Repeat values; reading hits walks the block.The block can contain more entries than unique result strings. Hits are found as they are read: 16 on the first read, the rest only when a read goes past them. Every comparison and every hit reads ByPrefix to reach its string. A result kept alive keeps its Snapshot’s arrays alive.
Ordinary writeUpdate the live HashSet, copy small delta arrays into their two sorted orders, publish.Copying grows with pending changes; it is not a constant-cost append.
Threshold writeAlso allocate and fill all three new Base arrays through Merge, renumbering every substring entry.That write takes longer and temporarily keeps old and new arrays alive.
RepeatAt for long textAt every starting position, compare against every earlier starting position.For a long repetitive string such as 10,000 A’s, common-prefix comparisons can be long too. Worst-case work per item grows cubically in its length.

The code is especially suited to short identifiers. The bucket construction still handles all UTF-16 code units, but long names or highly repetitive text change the memory and build-time tradeoffs. The original strings are reused, yet the starting-position structs, arrays, live set, deltas, result lists, and temporary copies all consume memory. See the measured benchmark results for context; the examples here illustrate behavior, not performance measurements.

09

Now the source has landmarks

Open SortedArrayIndex.cs alongside this page. The names below connect each piece of the implementation to an example you have just followed.

Every algorithm and helper in the file
Source nameRemember it through this exampleWalkthrough
Constructor · _items[US99, GB19, US99, US12] becomes three unique strings before building.01
Build · SnapshotConstruct [GB19, US12, US99], [US12, GB19, US99], and twelve starting-position entries numbered by ByPrefix position.02
SortedSubstringsCount the three entries starting with '9', place them in [3, 6), then sort that bucket.02
PrefixOrderUS12 sorts before US99; both match the prefix "US".03
SuffixOrderUS12 precedes GB19 because the last character 2 precedes 9.02
Substring · SubstringOrder(2, 2) is US99 from offset 2, read through ByPrefix[2], and compares as "99"; equal text is tied by the original Key, then Id.04
IOrder · Boundary · FindBlockFind the gaps before US12 and after US99: [1, 3).03
GetByStartsWith · GetByEndsWithRead State once; search its prefix or suffix view, including deltas.05
Filter · RepeatAtFilter("9") skips US99’s later occurrence because length 1 ≤ Repeat 1.04
Hits · Count / indexer / FindUpToCount = 2 kept − 1 removed + 1 added; the first read walks the block to 16 hits (here all of them) and appends FR99: [GB19, FR99].04
Add · RemoveAdd FR77, remove FR77: the pending addition cancels itself.05
Delta.Contains / With / Without / Insert / RemoveBinary-search FR77’s place, copy new small arrays; never edit published arrays.05
WithDelta[US12, US99] − [US12] + [US55] becomes [US55, US99].05
MergeSortedFind US12 at 1 and US55’s insertion gap at 2 in the original array.06
Merged<T> · Count / indexer / GetEnumerator / ToArray / Copy / NewIndexesCount reads the plan; reading a value copies GB19, skips US12, inserts US55, copies US99. NewIndexes turns the plan into old → new numbers: [0, −1, 2, 1].06
Publish · MergeThresholdAt a million live strings, 7,812 pending changes trigger a merge before publishing.06
Merge · SubstringsOfRemove US12’s four entries, insert US55’s four (numbered 3, past the old ByPrefix), renumber every entry to the new ByPrefix, then clear the deltas.06
State · _writeLock · Volatile.Read / WriteReader A can keep US12; Reader B starting after its removal sees only US99 for "US".07
DisposeAsyncReturns an already-completed ValueTask. There are no files, database handles, or worker tasks to close.—
A small glossary, using the same strings
Array
An ordered sequence of slots: [GB19, US12, US99].
Item number
A string’s position in ByPrefix: GB19 0, US12 1, US99 2. Substring entries store it instead of the string.
Offset
A starting position inside a string. In US99, offset 2 points to the first 9. These positions count UTF-16 code units; some visible Unicode characters occupy two.
Block / range
Neighboring array positions. [1, 3) includes positions 1 and 2.
Span
A view over existing contiguous memory, such as the characters "99" at the end of US99, without allocating that text as a new string.
ArraySegment
A window described by array, starting position, and count. The US block is a window starting at 1 with count 2.
Delta
The pending difference from Base: for example Added [FR77] and Removed [US12].
Snapshot
The three Base arrays built together. A State pairs one Snapshot with one Added delta and one Removed delta.
Materialize
Actually allocate and fill the planned result array, such as [US55, US99].
Common prefix
The shared beginning of two texts: "9" and "99" share one character.

You can now trace a string through the whole class.
Arrange the text → locate a matching block → handle duplicates and changes → return a stable result.

Back to the first example ↑