"US" → US12, US99
Sort by reading from the left.
ByPrefix: the US strings sit together.
A VISUAL GUIDE TO SortedArrayIndex.cs
Start with GB19, US12, and US99. See how this class arranges them, finds them, and keeps searching while the collection changes.
Arrange once. Find the edges. Return the block.
Part 2 of Search, illustrated · Play / pause and step controls · Exact string examples
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:
Sort by reading from the left.
ByPrefix: the US strings sit together.
Sort by reading from the right.
BySuffix: strings ending in 9 sit together.
Arrange the text starting at each position.
Substrings: find the block, then remove repeated hits.
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.
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.
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.
For US12, read 2 → 1 → S → U. For GB19, read 9 → 1 → B → G. For US99, read 9 → 9 → S → U.
| Original string | Read from the end | Why it is here |
|---|---|---|
US12 | 2 1 S U | Last character 2 comes before 9. |
GB19 | 9 1 B G | Tied on the last 9; next character 1 comes before 9. |
US99 | 9 9 S U | Follows 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.
To find "S9" inside US99, make the text at position 1 searchable. The same idea applies at every position:
| Stored entry | Text used for sorting | What it can find |
|---|---|---|
(US99, 0) | US99 | Fragments starting at U, such as "US". |
(US99, 1) | S99 | Fragments 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.
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.
start[c + 1]++ counts how many entries begin with character c. For '9', the count is 3.start['9'] = 3, start['9' + 1] = 6. Its reserved slice is [3, 6).next starts as a copy of start. Each '9' entry occupies the next free position in that tray; incrementing next['9'] moves its cursor.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.
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.
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.
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.
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.
~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.
~(−2) gives 1The ~ 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.
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.
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:
| Position | Text being compared | Stored (Item, Offset) · its string | Repeat |
|---|---|---|---|
| 0 | 12 | (1, 2) US12 | 0 |
| 1 | 19 | (0, 2) GB19 | 0 |
| 2 | 2 | (1, 3) US12 | 0 |
| 3 · start | 9 | (0, 3) GB19 | 0 → keep |
| 4 | 9 | (2, 3) US99 | 1 → skip for "9" |
| 5 | 99 | (2, 2) US99 | 0 → keep |
| 6 · end | B19 | (0, 1) GB19 | 0 |
| 7 | GB19 | (0, 0) GB19 | 0 |
| 8 | S12 | (1, 1) US12 | 0 |
| 9 | S99 | (2, 1) US99 | 0 |
| 10 | US12 | (1, 0) US12 | 0 |
| 11 | US99 | (2, 0) US99 | 0 |
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.
Text: "99"
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.
fragment.Length > Repeat.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.
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.
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.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.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.
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 > 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.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.
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:
The last built arrays.
New strings absent from Base.
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.
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.
| Operation | Added afterward | Removed afterward | Why |
|---|---|---|---|
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.
Suppose Added is [US55] and Removed is [US12]. WithDelta finds the "US" block separately in Base, Removed, and Added:
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.
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.
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].
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).
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.
| Live unique strings | Count / 128, rounded down | Merge at this many pending items |
|---|---|---|
| 3 | 0 | 256 |
| 100,000 | 781 | 781 |
| 1,000,000 | 7,812 | 7,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 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 number | String | New number |
|---|---|---|
| 0 | GB19 | 0 |
| 1 | US12 | removed (−1) |
| 2 | US99 | 2 |
| 3 · added | US55 | 1 |
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.
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.
Volatile.Read(ref _state) gives it the old State. Its Base, Added, and Removed all come from that same State._writeLock, it changes _items and creates a State with US12 in Removed. The old State and arrays remain unchanged.Volatile.Write publishes the complete new State. No search sees a half-updated combination of arrays.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.
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.
Start with [GB19, US12, US99]. Call Remove("US99"), then Add("FR99"), then Filter("9"). Here is every stage working together:
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 → PublishFilter 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)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>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.SortFR99.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(...)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 → FindUpToWith 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.
| Operation | Work performed | Tradeoff |
|---|---|---|
| Build | Sort 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 / ends | Two 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. |
| Contains | Two 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 write | Update 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 write | Also 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 text | At 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.
Open SortedArrayIndex.cs alongside this page. The names below connect each piece of the implementation to an example you have just followed.
| Source name | Remember it through this example | Walkthrough |
|---|---|---|
| Constructor · _items | [US99, GB19, US99, US12] becomes three unique strings before building. | 01 |
| Build · Snapshot | Construct [GB19, US12, US99], [US12, GB19, US99], and twelve starting-position entries numbered by ByPrefix position. | 02 |
| SortedSubstrings | Count the three entries starting with '9', place them in [3, 6), then sort that bucket. | 02 |
| PrefixOrder | US12 sorts before US99; both match the prefix "US". | 03 |
| SuffixOrder | US12 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 · FindBlock | Find the gaps before US12 and after US99: [1, 3). | 03 |
| GetByStartsWith · GetByEndsWith | Read State once; search its prefix or suffix view, including deltas. | 05 |
| Filter · RepeatAt | Filter("9") skips US99’s later occurrence because length 1 ≤ Repeat 1. | 04 |
| Hits · Count / indexer / FindUpTo | Count = 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 · Remove | Add FR77, remove FR77: the pending addition cancels itself. | 05 |
| Delta.Contains / With / Without / Insert / Remove | Binary-search FR77’s place, copy new small arrays; never edit published arrays. | 05 |
| WithDelta | [US12, US99] − [US12] + [US55] becomes [US55, US99]. | 05 |
| MergeSorted | Find US12 at 1 and US55’s insertion gap at 2 in the original array. | 06 |
| Merged<T> · Count / indexer / GetEnumerator / ToArray / Copy / NewIndexes | Count 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 · MergeThreshold | At a million live strings, 7,812 pending changes trigger a merge before publishing. | 06 |
| Merge · SubstringsOf | Remove 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 / Write | Reader A can keep US12; Reader B starting after its removal sees only US99 for "US". | 07 |
| DisposeAsync | Returns an already-completed ValueTask. There are no files, database handles, or worker tasks to close. | — |
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.