Skip to content

Latest commit

 

History

History
224 lines (146 loc) · 16.4 KB

DataStructures.md

File metadata and controls

224 lines (146 loc) · 16.4 KB

Data structures

FastData selects a structure automatically by default. Callers can also force a structure through the CLI, source generator attributes, or library configuration where that surface exposes the structure.

Automatic selection is data-dependent. The important inputs are key count, key type, density, range count, whether values are attached, whether approximate matching is allowed, and whether hash codes are collision-free for the dataset.

Selection summary

Numeric keys are considered in this order:

  1. SingleValue
  2. Range
  3. BloomFilter
  4. BitSet
  5. Conditional
  6. RrrBitVector
  7. EliasFano
  8. HashTablePerfect
  9. Hyble
  10. HashTable
  11. BinarySearch
  12. Array

String keys are considered in this order:

  1. SingleValue
  2. BloomFilter
  3. KeyLength, then KeyLengthBuckets
  4. Conditional
  5. HashTablePerfect
  6. Hyble
  7. HashTable
  8. BinarySearch
  9. Array

These lists describe selection priority, subject to enabled structures, required capabilities, and applicability limits. If construction fails during automatic generation, that structure is disabled and selection continues. StructureConfig.Default controls most automatic thresholds. The defaults favor simple branch-based code for small datasets, dense bit-level structures for suitable integral data, and hash tables for larger or irregular data.

Complexity and memory model

Complexity below is the amortized time for a single query after generated code has been loaded. Memory describes the generated lookup data for keys and lookup metadata only. Value storage is intentionally ignored, even for structures that support key/value lookup. The formulas also ignore executable instructions, method metadata, array/object headers, alignment padding, and target-runtime string/object overhead. Those costs differ by language and runtime. Packed-word formulas below use canonical storage widths; type reduction can further shrink emitted metadata.

n means the number of stored keys. Average memory assumes large n, so word-rounding effects such as ceil(... / 64) are ignored. For fixed-width numeric keys, one key slot is 8 bits for byte/sbyte, 16 bits for char/short/ushort, 32 bits for int/uint/float, and 64 bits for long/ulong/double. For strings on a 64-bit target, use 64 bits/key for a C# string reference or 128 bits/key for a C++ std::string_view / Rust &str, then add string literal payload bits.

TypeReductionEnabled is enabled by default. When enabled, generated integral metadata uses the smallest compatible built-in fixed-width type that covers the actual emitted values. Unsigned fields remain unsigned, while sentinel-bearing and signed-arithmetic fields retain signed storage; nonnegative GPerf association values may switch from signed to unsigned storage. This includes indexes, offsets, displacements, cached hashes, range boundaries, model intercepts, and packed-word arrays. Lookup code widens reduced values before arithmetic or bit operations. Disabling type reduction preserves each structure's canonical metadata types.

Array

  • Supports: Numeric and string keys
  • Values: Yes
  • Complexity: O(n)
  • Compressed: No

Array emits a linear scan over the keys. It is mostly useful when explicitly requested or as a simple baseline. Early exits can make it faster than a plain runtime array lookup for rejected keys.

For integral arrays with more than eight keys, the array lowerer emits four key checks per iteration and handles the tail in slot order.

Shared IR packs ordinal UTF-16 scans of 2–64 keys when guards prove a common length of one, two, or four code units. It reads the query once and scans packed words in slot order. Key access and enumeration use the stored strings.

BinarySearch

  • Supports: Numeric and string keys
  • Values: Yes
  • Complexity: O(log n)
  • Compressed: No

BinarySearch sorts the keys at generation time and emits binary-search logic. It is useful when predictable memory usage matters and logarithmic lookup cost is acceptable.

For sorted integral keys, the binary-search lowerer fixes the emitted probe count from the table size. Frontend contexts carry their sorted-order guarantee. Other contexts use this specialization only after their key order is verified. A final equality check confirms the candidate.

For integral keys up to 32 bits, the emitted search advances the binary-search index using the sign of the widened pivot-minus-key difference.

BinarySearchInterpolation

  • Supports: Numeric keys
  • Values: Yes
  • Complexity: O(log log n) on evenly distributed data; worst-case O(n)
  • Compressed: No

BinarySearchInterpolation uses the numeric value distribution to estimate the next probe location. It is useful for numeric datasets with a relatively even spread.

BitSet

  • Supports: Integral numeric keys
  • Values: Yes
  • Complexity: O(1)
  • Compressed: Yes: 64 * ceil(R / 64) bits, where R = (max - min) + 1

BitSet maps keys to positions in the observed range. Shared IR folds one-word occupancy loads to a mask. Keyed tables store values by numeric offset, outside the space estimate above. Consecutive keyed ranges omit occupancy storage. A bounded sparse cursor uses trailing-zero counts to scan whole words, with density limits of one quarter for one word and one eighth for multiple words.

BloomFilter

  • Supports: Numeric and string keys
  • Values: No
  • Complexity: O(1)
  • Compressed: Yes: 64 * ceil((10 * n) / 64) bits

BloomFilter is selected only when approximate matching is allowed. Explicit StructureTypeOverride = StructureType.BloomFilter also requires AllowApproximation = true, including when selecting another candidate from reusable analysis; otherwise generation or analysis throws InvalidOperationException. The current implementation allocates about 10 bits per key, then sets two bits inside one selected 64-bit word. The word index and both bit positions are derived from the same hash value, so the false-positive rate is closer to 3-5% on typical large sets than the roughly 1% expected from an optimal 10-bit/key Bloom filter. It is valid for compact membership pre-filtering when false positives are acceptable, but not for exact key/value lookup or callers that require a specific false-positive bound. RoundModuloToPowerOfTwo is enabled by default, so the bitset word length can be rounded up to the next power of two if the extra word count is within RoundModuloToPowerOfTwoThreshold. The threshold compares (rounded - original) / rounded, so the default 0.125 allows the added slots to occupy at most 12.5% of the rounded table (about 14.3% growth relative to the original size).

Conditional

  • Supports: Numeric and string keys
  • Values: Yes
  • Complexity: O(n)
  • Compressed: No

Conditional emits language-level conditions or switches. It is the default choice for small datasets because compilers can optimize the emitted branches well. The default item-count limit is conservative because branch-heavy code becomes slower as the set grows.

For 16–256 int keys, the shared optimizer can replace the lookup switch with a rank calculation. The key span, after any power-of-two stride normalization, must have at most four positions per key. The rewrite preserves slot order.

The shared optimizer can also compute the enumeration key directly from its slot when 16–256 int keys form an arithmetic progression in slot order.

Membership-only maps with at most 64 normalized positions can omit the rank table when earlier guards reject every hole. Normalization and bounds still reject out-of-range keys.

ConstMap

  • Supports: Numeric and string keys
  • Values: Yes
  • Complexity: O(1)
  • Compressed: Yes. Approximately 1.125 * n * candidateBits bits for large datasets

ConstMap uses a binary-fuse XOR table to recover a candidate ordinal with one generated base hash, a seeded finalizer, and three table reads. The ordinal indexes a compact key or key/value entry. Generated code bounds-checks the ordinal and compares the complete key, so membership and key/value misses are exact rather than fingerprint-based. This also allows arbitrary generated value types instead of restricting values to XOR-compatible integers. The construction follows Binary Fuse Filters: Fast and Smaller Than Xor Filters.

The canonical context stores 32-bit cells. With type reduction enabled, generated cells use the smallest unsigned built-in type covering the constructed table values, commonly 8 bits through 256 keys, 16 bits through 65,536 keys, and 32 bits above that. Key and value storage is excluded from the formula, consistent with the memory model above.

Construction is deterministic and retries bounded seeds when the binary-fuse graph cannot be peeled. It fails when two stored keys have the same generated 64-bit base hash because no seeded permutation can separate them. ConstMap is currently available only when explicitly requested; automatic selection continues to use the established structures until cross-language benchmark thresholds are available.

EliasFano

  • Supports: Integral numeric keys
  • Values: No
  • Complexity: O(1 + local high-bucket scan), with samples bounding zero-selection work; worst-case O(n) for highly clustered values
  • Compressed: Yes. 64 * ceil(upperBitLength / 64) + 64 * ceil((n * lowerBitCount) / 64) + (32 * sampleCount) bits

EliasFano stores sparse monotonic integer sets in a compressed representation. SkipQuantum is 128 by default. It stores upper bits, optional lower bits, and 32-bit sample positions.

HashTable

  • Supports: Numeric and string keys
  • Values: Yes
  • Complexity: O(1) amortized; worst-case O(n) if all entries collide into one bucket
  • Compressed: No

HashTable is the chained fallback after Hyble in automatic selection. It emits a bucket array and an entry array. Bucket indexes use the smallest unsigned type covering the actual bucket values, while Next uses the smallest signed type covering its actual values and the -1 sentinel. Cached hashes use the smallest unsigned type covering the generated hashes. FastData first computes the base bucket length as ceil(n * HashTableCapacityFactor). OptimizeHashTableBucketSize is enabled by default; when enabled, FastData treats the base length as a starting point and scans a bounded set of larger candidate bucket counts, choosing a size with fewer or acceptable collisions. RoundModuloToPowerOfTwo is enabled by default and runs after bucket-size optimization, so B can be rounded up to the next power of two if the extra bucket count is within RoundModuloToPowerOfTwoThreshold and rounding does not increase collisions. Each entry stores the key, a Next index for separate chaining, and an optional hash code. Numeric keys use identity-style hashing where possible. String keys use either the default string hash or a dataset-specific hash expression when analysis is enabled.

HashTableCompact

  • Supports: Numeric and string keys
  • Values: Yes
  • Complexity: O(1) amortized; worst-case O(n) if one bucket contains all entries
  • Compressed: No

HashTableCompact stores two bucket arrays, bucketStarts and bucketCounts, then stores all entries for a bucket contiguously. Bucket starts, counts, and cached hashes use type-reduced metadata when enabled. Entries do not need a Next index, so this saves per-entry memory when the two bucket arrays are cheaper than storing one next pointer per entry.

HashTablePerfect

  • Supports: Numeric and string keys
  • Values: Yes
  • Complexity: O(1)
  • Compressed: No

HashTablePerfect requires collision-free placement at the final capacity. It starts at ceil(n * HashTableCapacityFactor) and shares HashTable sizing and rounding. Lookup indexes keys and optional values by hash % B.

Identity-hashed integer lookups compare the stored key directly. Empty slots hold a real key that hashes to its occupied slot. Other key types cache hashes and reserve an empty-slot sentinel. Type reduction picks the smallest unsigned type that fits.

Hyble

  • Supports: Numeric and string keys
  • Values: Yes
  • Complexity: O(1)
  • Compressed: No

Hyble constructs a displacement-based perfect placement from base hashes, a seed, and per-bucket displacements. It emits keys in their final positions, optional values, and cached hashes for string keys. Lookup computes the candidate position and verifies the stored key. Construction retries a bounded set of seeds and can fail; automatic generation then disables that structure and tries the next compatible choice. Hyble does not advertise enumeration or direct-access capabilities.

KeyLength and KeyLengthBuckets

  • Supports: String keys
  • Values: Yes
  • Complexity: O(1)
  • Compressed: No

KeyLength uses string length as the index when every key length is unique and the length range is dense enough. The generated key table has one slot for every length in [minLength, maxLength], so gaps still consume key slots. Empty length slots do not add string payload. With values, it also emits a type-reduced unsigned offset array of length L = maxLength - minLength + 1 and a compact value array of length n, but value-related storage is not included above.

KeyLengthBuckets groups keys contiguously by encoded length and scans only the matching bucket. The lowerer checks the bucket offsets and can unroll scans of up to five keys or pack adjacent byte offsets. When the preceding length guards prove that a bucket exists, the emitted lookup can compute regular or periodic offsets directly. The reference lookup retains the original offset table and scan. Automatic selection requires more than one occupied length, at most five keys per length, and at least 20% occupancy across the observed length range.

Range

  • Supports: Integral numeric keys
  • Values: No
  • Complexity: O(r) for fewer than eight ranges; O(log r) otherwise
  • Compressed: Yes. 2 * r * boundaryBits where r is the number of ranges and boundaryBits is the emitted boundary width (keyBits when type reduction is disabled)

Range stores consecutive integral keys as ranges. For a single range, the generated code embeds the start/end constants directly in the comparison. For multiple ranges, it emits separate start and end arrays using the smallest same-signedness type that covers every boundary. Membership uses an early-terminating linear scan for fewer than eight ranges and binary-searches the range starts otherwise.

Automatic selection requires membership-only integral data and applies the configured range-count limits. A single range is always accepted because it is emitted as two constants. Multiple ranges are accepted only when their 2 * r endpoints use fewer key slots than the original n keys (2 * r < n), preventing mostly-singleton datasets from being expanded by range encoding.

RrrBitVector

  • Supports: Integral numeric keys
  • Values: No
  • Complexity: O(1) for dense blocks; O(log B) for sparse blocks, followed by a direct bit test. B is the number of occupied blocks.
  • Compressed: Empty blocks can be omitted. Dense storage uses 2 * C bytes and sparse storage uses (2 + indexBytes) * B bytes, where C = floor((max - min) / 15) + 1 and indexBytes is 1, 2, 4, or 8 with type reduction enabled, or 8 otherwise.

RrrBitVector uses raw 15-bit masks in 16-bit words. Explicit class/offset contexts remain supported by all generators; newly constructed vectors use masks.

Layout selection compares the generated payload and block-identifier widths. Sparse storage is selected when its array payload is smaller than dense storage, or when the total block count exceeds int.MaxValue. Equal costs use dense storage for direct indexing. Sparse lookups binary-search sorted occupied block identifiers and then test the mask.

Construction groups sorted keys by block identifier and accumulates one mask per occupied block. Block identifiers stay unsigned and 64-bit until resolved to an array position, allowing the full signed and unsigned 64-bit domains, including both extrema.

SingleValue

  • Supports: Numeric and string keys
  • Values: Yes
  • Complexity: O(1)
  • Compressed: No

SingleValue is selected when the dataset contains one unique key. It emits a direct equality check instead of a full collection structure.

Comparison

The graph below shows which data structure is the fastest for a given number of keys in one benchmark scenario. The Y-axis is the number of queries per second (QPS). The X-axis is the number of keys.

StructuresGraph.png

Use the graph as a broad intuition, not a fixed rule. FastData's automatic selection also accounts for data shape, key type, density, ranges, values, and configured limits.