Search, illustrated

A VISUAL TOUR OF search-algorithms

Seven ways to find
a string.

Three questions (starts with, ends with, contains) asked of 100,000 real ISINs while the data keeps changing. See how each approach answers them, how much work it took to make two general-purpose engines fast, and why a few sorted arrays end up winning.

Start with the contract
ISearchAlgorithm
IReadOnlyList<Entry> GetByStartsWith(string prefix);   // "US"   → US0378331005, …
IReadOnlyList<Entry> GetByEndsWith(string suffix);     // "1005" → US0378331005, …
IReadOnlyList<Entry> Filter(string fragment);          // "7833" → US0378331005, …
void Add(Entry item);
void Remove(Entry item);

One interface. Seven implementations. Same data, same queries, same machine.

00

What we are testing

Every algorithm implements ISearchAlgorithm. An Entry(Key, Id) is what a query matches (Key) and what the caller gets back to find its entity (Id). The rules are the same for all seven:

  • Ordinal and case-sensitive. "us" does not start with "US". No culture rules, no normalization.
  • Result order is free. An index may return hits in whatever order is cheapest.
  • Everything is concurrent. Searches run while Add and Remove change the data, and a search that starts after a write returned must see it. Each implementation owns its synchronization.
  • Same answers. dotnet test checks every implementation against a plain LINQ scan, also after adds and removes.
THE DATA

Real ISINs

~9.4 million unique 12-character securities identifiers from GLEIF's ISIN→LEI mapping, such as US0378331005.

Medium = a seeded random sample of 100,000. Small (10k) is a subset of it, Huge (1M) a superset.

The Updates chart also runs on ~3.4 million legal entity names from GLEIF, such as Whisky & Genuss Dresden GmbH: 26 characters on average, up to 307, in many scripts.

THE QUERIES

3–6 character cuts

Prefixes, suffixes and middle fragments cut from random items with a fixed seed, so every algorithm answers exactly the same queries.

Short queries are the hard ones: they match many items.

THE HARNESS

BenchmarkDotNet

Mean time per operation and bytes allocated. A separate process per index measures retained memory.

Apple M2, 8 cores.

The scenarios behind the charts in chapter 07
ScenarioWhat one measured operation isWhy it matters
Single queryOne StartsWith, EndsWith or Filter call and its Count, nothing else running.Pure search cost. A result that finds its hits only when they are read (the sorted array’s) skips that work here; Typeahead reads them.
Under writesThe same single query while a background writer performs 1,000 updates per second (each one Remove + Add).Live data: indexes that must refresh, merge or lock pay here.
TypeaheadOne search per keystroke of a 3–6 character query, reading only the first 10 hits.A search box. Indexes that copy every hit up front pay for hits nobody reads.
BuildThe constructor: index 100,000 entries from scratch.Startup and rebuild cost.
Add / RemoveOne write, single-threaded.The cost of keeping the index live.
UpdatesOne update (Remove + Add), 10,000 in a row, at 100,000 and 1,000,000 entries, on ISINs and on legal entity names.Sustained writes, including the batched work (merges, compactions) that a few writes never trigger.
MemoryBuild in a fresh process, then measure retained heap, process RSS and files on disk.What the index costs to keep around.
01

Linear scan: check everything, every time

The baseline has no index at all. LinearScan keeps a HashSet<Entry> and, for each query, asks every item the question directly: Key.StartsWith(prefix), Key.EndsWith(suffix) or Key.Contains(fragment). It is short, obviously correct, and the reference the tests compare everyone else against.

private List<Entry> FindAll(Func<string, bool> match)
{
    _lock.EnterReadLock();
    try { return _items.Where(x => match(x.Key)).ToList(); }
    finally { _lock.ExitReadLock(); }
}
WATCH THE SCAN

Six items, six checks, whatever the question

LinearScan.FindAll

The cost is the number of items times the cost of one string check, for every query. At 100,000 ISINs that is 100,000 checks even when the answer is empty. Writes are cheap (one hash-set operation) but must take the lock exclusively, so a write waits for every running search to finish, and new searches wait behind the write.

02

Concurrent scan: drop the lock, keep the scan

ConcurrentLinearScan asks the same question of every item, but stores them in a ConcurrentDictionary<Entry, byte>. Enumerating it is lock-free, so searches never block and writers never wait for readers. The price is weaker consistency: a search running during writes may or may not see them.

ONE WRITE, TWO SEARCHES

Who waits for whom?

ReaderWriterLockSlim vs ConcurrentDictionary
Removing the lock did not make searches faster. The scan is still a scan, and walking a ConcurrentDictionary visits one heap-allocated node per item through its buckets, where a HashSet walks one dense array. In the measurements the concurrent version is the slower of the two for single queries. Locking was never the bottleneck; touching every item was.
03

Naive RocksDB: sorted keys, used for one question

RocksDB is an embedded key-value store that keeps keys sorted by their bytes. Writes land in an in-memory table and are later written out as sorted files; an iterator merges them into one ordered view. NaiveRocksDbIndex is the textbook setup: default options, one Put per entry, and one key per entry:

US990xFF00 00 00 05Key as UTF-8 · separator (never in UTF-8) · Id, 4 bytes · value: empty

Because the keys are sorted, StartsWith is easy: seek to the first key ≥ the prefix and read forward until a key stops matching. EndsWith and Filter get no help from that order, so the naive version reads every key and checks it in C#.

DRIVE THE ITERATOR

Seek once, or read everything?

Iterator.Seek · Next
iterator positionhitDimmed = not read

Every key read crosses from .NET into the native library, copies the key into a new byte[] and decodes a new string. A full scan pays that 100,000 times. The defaults cost more elsewhere too: a write-ahead log for an index that is rebuilt anyway, and a build that puts entries one at a time and never compacts.

04

Naive Lucene: a search engine, used literally

Lucene is an inverted index: a sorted dictionary of terms, each pointing to the list of documents that contain it (its postings). NaiveLuceneIndex indexes each entry as one document whose whole Key is a single term, and asks wildcard questions: US*, *9, *S9*.

A WildcardQuery becomes an automaton that is walked against the term dictionary. A pattern with a fixed start can skip straight to its region of terms. A pattern starting with * cannot: it must test every term. And each search here does more than walk terms:

FOLLOW ONE SEARCH

Filter("S9") → WildcardQuery("*S9*")

DirectoryReader.Open · Search · Doc

Each step is reasonable for full-text search, where you want the ten best-scoring documents. Here every hit is wanted, nothing needs a score, and the reader is reopened per query. So the textbook version pays for ranking, for loading stored documents, and for refreshing the index on every call.

05

What it took to make Lucene fast

Lucene can be fast here, but not by tuning one setting. Almost every default the naive version leans on had to be replaced, each change found with a profiler and kept only if a benchmark agreed.

9optimization commits, each one profiled and measured
74 → 226lines of C#, including a custom hit collector
3n-gram fields per document instead of one term
—Filter, naive → tuned (Medium, single query)
THE CORE IDEA

Index every answer as its own term

EdgeNGramTokenizer · NGramTokenizer
Every layer changed: naive → tuned
LayerNaiveLuceneIndexLuceneIndex
QueryWildcardQuery, leading * walks every termOne TermQuery on a precomputed prefix, suffix or n-gram term; longer queries look up 6 chars and verify the rest
ReaderNew near-real-time reader per searchSearcherManager, refreshed only when a write happened since the last refresh
Collecting hitsA ranked top-N queue as large as the index (Search(query, int.MaxValue))A custom ICollector: no scoring, no queue, result list sized from the term's doc count
Reading hitsLoad each hit's stored documentA per-segment Entry[] table, indexed by doc number, built once from the id terms
StorageFSDirectory (buffered file reads on macOS), compound filesMMapDirectory behind NRTCachingDirectory, no compound files
BuildOne thread, many segmentsAll cores, 256 MB buffer, per-thread flushes, ForceMerge(1)
The commit trail, with what each step measured
  1. Collect ids, reuse the searcher. Collector reads ids without scoring or stored fields; SearcherManager shares one searcher and reopens only after unseen writes.
  2. Decode each id into one string, not a CharsRef plus char[]: 128 → 48 B per hit.
  3. Return existing string instances instead of decoded copies.
  4. StartsWith / EndsWith as one term lookup via edge n-grams; reuse tokenizers per thread. StartsWith 2,745 → 1,570 μs, EndsWith 17 → 9 μs.
  5. Per-segment id table indexed by doc number: a hit costs an array index.
  6. Parallel build, one segment, edges up to 6 chars. Each extra segment cost every query a term lookup (EndsWith was 10× slower at 13–19 segments). 1M build 51.6 → 23.2 s.
  7. MMap behind NRT caching, no compound files. Buffered reads were 44–70% of every search. Under 1,000 writes/s: EndsWith 4,101 → 92 μs.
  8. Size result lists up front from the term's doc count: growing them was 56–63% of a large search.
  9. Per-thread flushes during build: Medium build ~3.1 → 2.6 s.

From the repository's commit messages; the numbers were measured at the time of each commit, on earlier versions of the benchmark.

What it still costs. The n-gram fields multiply the index: a 12-character ISIN is indexed as 57 n-grams (lengths 1 to 6) plus 6 prefix and 6 suffix edges. The build is the slowest of all seven, and every write makes the next search refresh the reader. Under a steady stream of writes that refresh is where Lucene's time goes.
06

What it took to make RocksDB fast

RocksDB can only do one thing quickly: walk a range of sorted keys. So the fix is to turn all three questions into starts with questions, by writing each entry several times in shapes where the answer is a prefix. A 259-line plan came first; it checked the binding's API, the key encoding and the edge cases before any code was written.

76 → 294lines of C#, after a 259-line written plan
3column families: prefix, reversed, rotations
n + 2keys per entry (14 for a 12-char ISIN)
—Filter, naive → tuned (Medium, single query)
ONE ENTRY, n + 2 KEYS

Writing (US99, #5) so every question is a prefix

RocksDbIndex.Stage
Naive → tuned, layer by layer
LayerNaiveRocksDbIndexRocksDbIndex
Key spacesOne: the KeyThree column families: Key, reversed UTF-8 bytes, one rotation per character with a 2-byte Repeat in front
EndsWith / FilterRead every key, check in C#Seek to the prefix, stop at an upper bound (SetIterateUpperBound): only hits are read
Duplicates in Filter—Repeat sorts first in the key, so only buckets below the fragment's length are read and every key read is a hit
ConsistencyOne key per writeOne WriteBatch across all three families (atomic); one snapshot across Filter's buckets
BuildOne Put per entry, write-ahead log onParallel 4,096-entry batches, no WAL, then CompactRange to one sorted file per family
Storage optionsDefaultsShared 512 MB LRU block cache, no compression
ResultsNew byte[] and string per hitUtf8Hits: hit bytes back to back, decoded only when read
What it still costs. RocksDB has no "how many keys in this range" and no random access by position. A result's Count means stepping over every hit through the native binding, about 120 ns each. A one-character prefix that matches most of the data is a long walk, even when the caller reads only ten hits.
07

The numbers

All seven algorithms, one run, one machine, ISINs at Medium (100,000 entries) except "Updates", which also covers 1,000,000 entries and the names dataset. Bars are on a logarithmic scale: each gridline is ten times the previous one, otherwise the fastest results would be invisible. Shorter is better.

SortedArrayIndexTuned enginesNaive enginesScans
Show every number as a table
STARTS / ENDS WITH

Two binary searches win

The sorted array answers in under a microsecond and hands back a window onto its array without copying. The engines are fast only when few entries match: ISIN suffixes are selective, prefixes like US91 are not, and paying per hit makes RocksDB's StartsWith slower than a plain scan.

CONTAINS

The cost per hit decides

The sorted substring array and Lucene's n-grams beat the scans by more than an order of magnitude. RocksDB also reads only hits, but each one crosses into native code, so it lands close to the linear scan it was meant to replace. The sorted array's single query counts its hits without finding them; in Typeahead, which reads ten, it is still about six times faster than Lucene.

THE BILL

Speed is paid for elsewhere

Lucene has the slowest build by far and allocates gigabytes doing it. The sorted array pays on writes: most only copy its small sorted delta, but every few thousand a merge rewrites all three arrays (about 130 MB at 1,000,000 ISINs). Counted in, as in "Updates", it is the second slowest: RocksDB is slower, except at 1,000,000 ISINs, where the two tie. It also keeps everything on the heap, where Lucene and RocksDB keep files on disk.

BenchmarkDotNet short in-process job, 3 warmups and 5 iterations of 200 ms: good for orders of magnitude, not for small differences. Bars marked with a dash had no result.

08

Sorted arrays, in great detail

SortedArrayIndex keeps three sorted arrays (by prefix, by reversed suffix, and every starting position inside every key), finds each answer as one contiguous block with two binary searches, and collects writes in a small sorted delta that is merged in batches, while readers keep a consistent snapshot.

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

Arrange once. Find the edges. Return the block.

Read the step-by-step walkthrough

Nine chapters with step players: building the views, finding both edges, de-duplicating contains hits, writes without rebuilding, merging, and readers versus writers.