Skip to content

Faster name lookups, lazy name tables and a cacheable booster generator - #137

Open
lsoft wants to merge 14 commits into
xin9le:mainfrom
lsoft:perf/lookup-and-generator
Open

lsoft wants to merge 14 commits into
xin9le:mainfrom
lsoft:perf/lookup-and-generator

Conversation

@lsoft

@lsoft lsoft commented Nov 27, 2026

Copy link
Copy Markdown

Hi, thank you for FastEnum! It is a fast and carefully built library, and the work of the v2.x releases (lazy Member<T> data, JIT-friendly helpers, Native AOT support) made it easy to build on. This PR is what came out of looking for CPU and memory savings in v2.1.0. Every change was measured first, and the ones that did not pay off were dropped.

Each commit is a separate piece of work

The commits are not steps of one change. Each one has its own goal, can be reviewed on its own, and its message explains the reason, the change and how it was measured. Feel free to take only some of them. The commits apply in order:

  • 11 and 12 rework the buffers that commit 2 introduced, so they need it.
  • 9, 10, 13 and 14 only add benchmark tooling and do not touch the library. If you would rather not have the Windows script in the repository, 9 can be left out.
# Commit What it does
1 Add benchmarks for name lookup worst cases, boosters and attributes New NonConstantInput scenarios that the commits below are measured with.
2 Choose the bucket of string dictionaries by a searched multiplier The bucket index was the low bits of (len << 16) ^ (first << 8) ^ (mid << 4) ^ last, which for small tables is only the last character (all DayOfWeek names share one bucket). Now it is multiply-shift with a multiplier chosen per table at creation. The first candidate equals the old mask, so a hit never costs more comparisons than before on average. Average comparisons per hit over 127 BCL enums: 1.77 → 1.27.
3 Compare ASCII names of 17-32 chars without OrdinalIgnoreCase The ASCII fast path of case-insensitive parsing covered 4–16 chars. About a fifth of BCL enum names are longer. 17–32 chars now use two overlapping 256-bit loads, or four 128-bit loads without AVX2.
4 Parse numbers and format undefined values without initializing EnumInfo TryParse("123") and ToString() of an undefined value through a booster no longer run the EnumInfo<T> static constructor just to read the type code.
5 Hold labels in an array indexed by the label index FrozenDictionary<int, string?> per member is replaced by a string?[] (sparse indexes fall back to a small pair array). Same lookup speed, less memory at the first GetLabel().
6 Build the lookup tables by name at their first use The case-sensitive and case-insensitive name dictionaries are built at the first name lookup, not in the EnumInfo<T> static constructor. An app that only formats values never builds them. Tier1 code still reads them as constants.
7 Test case-insensitive parsing of boosters against System.Enum Exhaustive tests of booster TryParse(ignoreCase: true) against Enum.TryParse.
8 Make the booster generator pipeline cacheable The transform returned GeneratorAttributeSyntaxContext, which never equals the previous run, so every edit in the IDE regenerated every booster. Now it returns equatable records. Diagnostics keep their original Location, so #pragma warning disable and .editorconfig still apply to FE0001–FE0004. The generated code is byte-for-byte the same.
9 Run the benchmarks pinned to the performance cores run-benchmarks.bat pins BenchmarkDotNet to the P cores of a hybrid CPU. Without it, two runs of the same code differed by 10–15%.
10 Compare with a baseline source tree in one benchmark run FASTENUM_BENCH_BASELINE=<other tree>\src\libs adds a baseline job built against another FastEnum source tree, so both versions run back to back in one run and get a Ratio column.
11 Take the buffers of the multiplier search from the stack Renting two same-size buffers from ArrayPool<int>.Shared made the pool keep per-core stacks (25 KB for the process). Buffers up to 2 KB now come from the stack.
12 Keep stackalloc and loops in separate methods OSR does not support stackalloc, so a method with both skipped Tier0 and was fully optimized on its first call: +2.4 ms of JIT on 20 enums. Now the two are in separate methods.
13 Benchmark every scenario over a corpus of 512 BCL enums One benchmark per scenario over 512 BCL enums × 64 inputs, so results do not depend on a few hand-picked enums.
14 Benchmark the first use of FastEnum over the corpus The same corpus as a cold start: a fresh process per measurement.

One note on the commit messages: the numbers in commits 2–8 were measured on an earlier revision of this series, which also had flat lookup tables (dropped, see below). The tables in this description are for exactly this series.

Results: v2.1.0 vs this PR

All runs measure both versions in one BenchmarkDotNet run (commit 10), pinned to the P cores (commit 9).

Environment: Intel Core Ultra 7 251HX (6 P cores of 18 logical CPUs), Windows 11, .NET 11.0.0, x86-64-v3.

Steady state, 512 BCL enums (Corpus)

Mean time of one operation over the whole corpus, from two independent runs:

Scenario v2.1.0 this PR Ratio (run 1 / run 2)
TryParse, existing names 3.19 ns 2.79 ns 0.88 / 0.86
TryParse, ignoreCase 6.51 ns 5.40 ns 0.83 / 0.80
TryParse, one character changed (typo) 5.29 ns 2.81 ns 0.53 / 0.52
TryParse, names of other enums 8.45 ns 6.26 ns 0.74 / 0.72
GetName 0.875 ns 0.870 ns 0.99 / 0.99
ToString 0.865 ns 0.849 ns 0.98 / 0.98

Hand-picked enums (NonConstantInput)

Benchmark v2.1.0 this PR Ratio
TryParse DayOfWeek 3.93 ns 2.03 ns 0.52
TryParse(ignoreCase) DayOfWeek 6.15 ns 3.45 ns 0.56
IsDefined(name) HttpStatusCode 2.51 ns 1.81 ns 0.72
TryParse HttpStatusCode 2.77 ns 2.02 ns 0.73
TryParse(ignoreCase) HttpStatusCode 4.06 ns 3.12 ns 0.77
TryParse(ignoreCase) ConsoleKey 3.90 ns 3.48 ns 0.89
TryParse / TryParse(ignoreCase) Fruits 1.03
GetName / IsDefined(value) / ToString / GetLabel / GetEnumMemberValue 0.96–1.02

Memory and first use

These numbers come from a small console profiler that is not part of this PR. It measures the first use of 20 BCL enums and reports the median of 11 processes.

Scenario v2.1.0 this PR
Only formatting (GetName), memory retained 251 KB 187 KB (−26%)
Formatting + TryParse + TryParse(ignoreCase), retained 251 KB 251 KB
First booster call on the numeric path 12.5 KB allocated, 5.3 ms 10.8 KB allocated, 2.3 ms
First GetLabel() over 64 members with two labels each 52 KB allocated, 4.7 ms 37 KB allocated, 1.4 ms

Booster generator

The IDE case was measured with CSharpGeneratorDriver on 50 boosters of 50 members, editing one file 40 times:

v2.1.0 this PR
Boosters regenerated per edit 50 of 50 0 of 50
Allocated per edit 13.8 MB 2.0 MB

Trade-offs

  • Misses of the synthetic Name_ inputs are 1.3–1.5x slower (about 1.15 → 1.5 ns). The old index put every one of them into the empty bucket of _; the new index spreads them over occupied buckets. Realistic misses are faster: the "typo" and "other enum" rows of the corpus table above.
  • The first name lookup costs a little more JIT. This is a one-time cost per process.
    • On the 512-enum corpus (ColdCorpus, 15 fresh processes each, StdDev about 3.5 ms): the first TryParse takes +4% (about +30 µs per enum), and all three operations in a row take +7% (+72 µs per enum).
    • The first GetName takes −3%.
    • Most of it is the two nested static constructors per enum type from commit 6 (about 1.2 ms per 20 enums) and the vector code of commit 3 (about 0.7 ms).
    • I tried reading the lazy tables without the nested classes. That saved about 1 ms of JIT but made case-insensitive parsing 3–5% slower, because a null check replaced a JIT constant, so it is not included.
  • The worst miss can compare more names. The multiplier search minimizes the comparisons for existing names, with the longest chain only as a tiebreaker. The longest chain can therefore get longer than with the old mask, and a miss that lands in it compares more names.
  • One exotic behavior change. An enum with a char or bool underlying type can be declared in IL, though not in C#. With such an enum, every call still throws TypeInitializationException, as before. The exception now names TypeCodeOf<T> (commit 4), or the lazy table classes (commit 6), instead of EnumInfo<T>.

How it was tested

Correctness

  • Every commit was checked out on its own, built, and passed all of FastEnum.UnitTests on net10.0 and net11.0. That is 635 tests up to commit 6 and 641 from commit 7, which adds the booster tests.
  • New tests:
    • IgnoreCaseEnum gets names of 24, 32 and 33 chars, so the exhaustive "every UTF-16 code unit at every position" test compares both new comparison paths and the 32/33 boundary with Enum.TryParse;
    • Generators/IgnoreCaseTests does the same for a generated booster;
    • AnnotationTests covers sparse label indexes (-1, 100) and undefined indexes.
  • Commit 3 also passes with DOTNET_EnableAVX2=0, which runs the 128-bit path.
  • No commit adds a compiler warning (checked per commit).
  • Commit 8:
    • the generated sources are byte-for-byte identical to v2.1.0;
    • FE0001 / FE0004 are reported at the same locations;
    • a consumer project with a non-partial booster fails with FE0001 and builds once FE0001 is suppressed with #pragma warning disable or with .editorconfig, the same as with v2.1.0.
  • The whole series also had two separate code review passes, done with Claude Code as well. Their findings are fixed in the commits they belong to:
    • diagnostic suppression in commit 8;
    • char/bool enums in commit 4;
    • an XML doc warning in commit 11;
    • an unquoted baseline path that broke the comparison when the path has a space, in commit 10;
    • three inaccurate comments.

Performance

  • BenchmarkDotNet with both versions in one run (commit 10). Each job has 2 process launches, to average out code placement.
  • Runs are pinned to the P cores (commit 9). Before that, the same code differed by 10–15% between runs, which is more than most of the effects here.
  • Corpus and ColdCorpus (commits 13–14) check the effect over 512 BCL enums, not just the hand-picked ones. The setup prints a checksum of the corpus, so all jobs are known to measure the same enums.
  • First-use time and memory were measured with the profiler mentioned above:
    • allocated bytes from GC.GetAllocatedBytesForCurrentThread();
    • retained bytes from GC.GetTotalMemory(true);
    • JIT method count and time from System.Runtime.JitInfo;
    • each JIT number is the median of 21 processes pinned to P cores.
    • The regression fixed in commit 12 was found by bisecting the JIT counts commit by commit.
  • Bucket quality (commit 2) was checked by counting the comparisons per lookup over the names of 127 BCL enums.

Dropped after measuring

  • A nested-switch case-insensitive parser in the generator: the generated method was no longer inlined and became 2.8 → 10.4 ns.
  • Flat lookup tables: −13% memory but slower misses.
  • Moving the rarely used fields of Member<T> (UTF-8 name, EnumMemberAttribute, labels) into a side object created on first access, to make Member<T> smaller: GetEnumMemberValue was 20% slower.

To reproduce the comparison:

git worktree add ..\FastEnum-base v2.1.0
set FASTENUM_BENCH_BASELINE=<full path>\FastEnum-base\src\libs
run-benchmarks.bat --filter *Corpus*

This work was done with Claude Code, and the commits carry a Co-Authored-By trailer. Every change was reviewed and measured as described above. Thanks again for the library and for maintaining it!

🤖 Generated with Claude Code

lsoft and others added 14 commits November 27, 2026 14:49
NonConstantInput gets scenarios that the following optimizations are measured with:
- TryParse / TryParseIgnoreCase for DayOfWeek (all names end with 'y') and ConsoleKey (names of 1-18 chars)
- TryParse of undefined names for HttpStatusCode
- TryParse / TryParseIgnoreCase through generated boosters (Fruits, HttpStatusCode, ConsoleKey)
- GetLabel (Colors enum with two labels per member) and GetEnumMemberValue

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The bucket was the low bits of the hash, (length << 16) ^ (first << 8) ^ (middle << 4) ^ last.
For a table of up to 16 buckets that is only the last character, and up to 256 buckets the first
character is ignored. All names of DayOfWeek end with 'y' and shared one bucket.

The index is now multiply-shift, (hash * multiplier) >> shift. The names are fixed on creation, so
up to 64 multipliers are tried and the one with the fewest comparisons for the keys wins (the total
of the positions in the chains, then the longest chain). The first candidate is 2^shift, which is
the same as the old masking, so a lookup of an existing name never costs more than before on
average. The longest chain can get longer, so a miss that falls into it may compare more names.

Average comparisons per hit over 127 BCL enums: 1.77 -> 1.27.
NonConstantInput: TryParse_DayOfWeek 4.43 -> 2.03 ns, TryParseIgnoreCase_DayOfWeek 6.41 -> 3.52 ns,
TryParse_Discontinuous 2.88 -> 2.03 ns. Misses like "Name_" went 1.2 -> 1.5 ns, because the old index
put all of them into the empty bucket of '_'.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The fast case-insensitive comparison covered only 4-16 chars; longer names went to
MemoryExtensions.Equals(OrdinalIgnoreCase). About a fifth of the names of BCL enums are longer
than 16 chars (e.g. NonAuthoritativeInformation). 17-32 chars are now covered by two overlapping
256-bit loads, or four 128-bit loads without AVX2.

Shorter than 4 chars was tried with two overlapping 32-bit loads, but it was as fast or slower
(3 chars: 1.51 -> 1.85 ns), so it stays on OrdinalIgnoreCase.

EqualsIgnoreCaseByLength (new), OrdinalIgnoreCase -> EqualsAscii:
  17 chars 2.64 -> 1.63 ns, 24 chars 2.69 -> 1.64 ns, 32 chars 2.79 -> 1.69 ns
NonConstantInput: TryParseIgnoreCase_Discontinuous (HttpStatusCode) 3.49 -> 3.09 ns (-11%), others within noise.

IgnoreCaseEnum gets names of 24, 32 and 33 chars, so ReplaceWithEveryCharacter checks both new
paths and the boundary against System.Enum. Tests pass with and without AVX2 (DOTNET_EnableAVX2=0).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…fo<T>

ToNumberString() and TryParseValue() switched on EnumInfo<T>.s_typeCode. They are also reached
through IFastEnumBooster<T> (TryParse of "123", ToString of an undefined value), so a booster user
paid for the static constructor of EnumInfo<T> just to read the type code: reflection over the
fields, Member<T> objects and all lookup tables.

The type code now lives in UnderlyingOperation.TypeCodeOf<T>. EnumInfo<T> reads it in its static
constructor, so on the reflection path it is always initialized before Tier1 compiles the callers
and JIT still folds the switch. Without that, ToString() of a defined value never ran
ToNumberString(), the whole switch stayed in the code (1,858 -> 3,064 B) and ToString_Discontinuous
got 8% slower.

An enum of char or bool (possible in IL, not in C#) made the static constructor of EnumInfo<T>
throw. TypeCodeOf<T> throws the same InvalidOperationException for it, so TryParse("1") still
throws TypeInitializationException instead of returning false. The exception now names
TypeCodeOf`1 (and, for names, the classes that read it) instead of EnumInfo`1.

Profiler, first booster call (TryParse "1" + ToString of an undefined value):
  allocated 19,648 -> 10,816 B (-45%), retained 16,296 -> 7,456 B (-54%), time 6.2 -> 2.4 ms
NonConstantInput ToString_* / Booster_*: within -2.5% .. 0%, code size unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Labels of each member were a FrozenDictionary<int, string?>, created at the first GetLabel():
an intermediate Dictionary<,>, the frozen arrays and an object, for one to three labels.

Labels are now a string?[] indexed by the label index; an undefined slot holds a sentinel string,
because null is a valid label. A negative or large index (beyond max(16, count * 2)) falls back to
an array of (index, value) pairs searched linearly. Duplicated indexes still throw ArgumentException.

The lookup returns the label or the sentinel instead of `bool TryGetLabel(..., out string?)`.
With the out parameter JIT kept the label on the stack in the inlined loop, and GetLabel got 25%
slower than FrozenDictionary.

Profiler, first GetLabel() of 64 members with two labels each:
  allocated 52,424 -> 37,440 B (-29%), retained 11,440 -> 6,696 B (-41%), time 4.6 -> 1.6 ms
NonConstantInput.GetLabel: 1.44 -> 1.45 ns (unchanged).
AnnotationTests cover sparse indexes (-1, 100) and undefined indexes of a dense array.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The static constructor of EnumInfo<T> built both string dictionaries for every enum type, even for
an application that only formats values (GetName / ToString / IsDefined(value)), and the
case-insensitive one even if ignoreCase is never used.

Each table now lives in a nested class with an explicit static constructor, so it is built at the
first IsDefined(name) / Parse / TryParse (with ignoreCase for the case-insensitive one). Tier1 code
compiled after that reads the field as a constant, the same as before. The classes are not
beforefieldinit on purpose: JIT may run such a static constructor while compiling a method that
refers to it, and TryParse() would build both tables again.

Profiler, first use of 20 BCL enums:
  GetName only: allocated 265,568 -> 215,368 B (-19%), retained 236,960 -> 186,760 B (-21%)
  + TryParse:   +25,584 B, + TryParse(ignoreCase): +25,656 B (the same tables, built later)
NonConstantInput TryParse* / IsDefinedName* / GetName*: within -2.4% .. +1.6%.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Generators/IgnoreCaseTests mirrors Reflections/IgnoreCaseTests for a generated booster of
IgnoreCaseEnum: as is / upper / lower / longer / shorter, and every UTF-16 code unit at every
position of every name, compared with Enum.TryParse(ignoreCase: true).

It was written to guard a change of the generated case-insensitive parsing (a nested switch on a
character folded by `| 0x20`). That change was dropped after profiling: the generated method grew
to 12 KB, was no longer inlined and made real calls to OrdinalIgnoreCase for every name, so
Booster_TryParseIgnoreCase_ConsoleKey went 2.8 -> 10.4 ns. The test stays.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The transform step returned GeneratorAttributeSyntaxContext as is. It holds the semantic model,
which is new for every compilation, so the value never equaled the previous run: on every edit in
IDE every booster was generated again and its source was replaced. The pipeline also combined
ParseOptionsProvider for LanguageVersion, which was not used.

The transform now extracts records compared by value (names as strings, EquatableArray<T> for
lists, the diagnostic as id + Location + argument), so the output step runs only when a booster
actually changes, and the pipeline no longer holds symbols, syntax nodes or old compilations.
The generated code is byte-for-byte the same.

The diagnostic keeps its Location as is: a location in source equals another one with the same
syntax tree and span, and the tree of a file stays the same object until the file is edited.
A location created again from the file path would not be in source, and the compiler would ignore
#pragma warning disable and .editorconfig severity for FE0001-FE0004.

GenBench (CSharpGeneratorDriver, 50 boosters x 50 members, median of 40 edits):
  edit an unrelated file: outputs Modified=50 -> Cached=50, 13.8 MB -> 2.0 MB allocated (-86%), 21.1 -> 14.6 ms
  edit the file of the enums: Modified=50 -> Cached=50, 14.0 MB -> 2.2 MB (-84%), 16.1 -> 5.9 ms
FE0001 / FE0004 are still reported at the same locations, and can still be suppressed with
#pragma warning disable or .editorconfig.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
On a hybrid CPU the scheduler moves a benchmark between P and E cores, and the mean of a run shifts
with the share of time spent on E cores: the same code measured 10-15% apart in two runs.

run-benchmarks.bat builds the benchmarks and starts them with `start /affinity <mask> /abovenormal`.
eng/get-pcore-affinity.ps1 prints the mask of the cores of the highest EfficiencyClass
(GetLogicalProcessorInformationEx), or nothing on a CPU whose cores are all equal.
The mask goes onto the host process, so every process BenchmarkDotNet starts inherits it before its
runtime starts; BenchmarkDotNet's own --affinity is applied later and is a signed 32-bit number.
FASTENUM_BENCH_AFFINITY overrides the mask (hex) or turns it off ("off").

Checked on this machine (6 P cores of 18 logical CPUs): the host runs with affinity 0x3C03 /
AboveNormal, and the benchmark process BenchmarkDotNet starts with 0x3C03 / High.

.gitattributes: *.bat and *.ps1 are checked out with CRLF; cmd.exe may fail to find a label for
goto / call in a batch file with LF line endings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Numbers of two separate runs drift on their own, so comparing them gives a confident wrong answer.
With FASTENUM_BENCH_BASELINE set to the src/libs directory of another tree (e.g. a worktree of the
previous release), BenchmarkConfig.ForComparison() adds two jobs:
- baseline: built with /p:FastEnumLibs=<that directory>, so it references that FastEnum.Core and generator
- current: this tree
Each benchmark runs with both back to back, in separate processes, and the table gets a Ratio.
Two launches per job average out the code / data placement fixed for a process; shorter iterations
keep a dozen benchmarks x 2 jobs at about 5 minutes.

    git worktree add ..\FastEnum-base v2.1.0
    set FASTENUM_BENCH_BASELINE=<full path>\FastEnum-base\src\libs
    run-benchmarks.bat --filter *NonConstantInput*

v2.1.0 vs this branch, 14 benchmarks, one run on P cores (4:57):
  TryParse_DayOfWeek                 3.95 -> 2.00 ns  0.51
  TryParseIgnoreCase_DayOfWeek       6.16 -> 3.53 ns  0.57
  IsDefinedName_Discontinuous        2.49 -> 1.74 ns  0.70
  TryParse_Discontinuous             2.64 -> 1.99 ns  0.75
  TryParseIgnoreCase_Discontinuous   4.07 -> 3.03 ns  0.75
  TryParseIgnoreCase_ConsoleKey      3.88 -> 3.49 ns  0.90
  TryParse_Continuous                1.95 -> 2.00 ns  1.02
  TryParse_Discontinuous_Undefined   1.13 -> 1.67 ns  1.48
  GetName / IsDefined(value) / ToString / GetLabel / GetEnumMemberValue: 0.99 - 1.01

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Building a string dictionary rented two int buffers from ArrayPool<int>.Shared at once: the
hashes and the bucket counts. The second buffer of the same size returned to the pool does not fit
its thread-local slot, so the pool creates its per-core stacks for that size and keeps them for the
process. At the first TryParse of 20 BCL enums that was 25 KB retained, which made the whole
change cost more memory than v2.1.0 when both kinds of name lookup are used.

Buffers of up to 512 ints (2 KB) now come from the stack; larger ones are still rented.

Profiler, first use of 21 BCL enums, cold ArrayPool, v2.1.0 -> this branch (median of 11 processes):
  first TryParse:         allocated 56,048 -> 30,800 B, retained 55,184 -> 30,008 B (before -> after this commit)
  all stages, retained:   v2.1.0 251,272 B, this branch 250,976 B (was 276,152 B)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The previous commit put stackalloc into Create() and ChooseMultiplier(), which also have loops.
OSR does not support stackalloc, so such a method skips Tier0 and is compiled with full
optimization at its first call. That cost 2.4 ms of JIT at the first use of 20 BCL enums.

The buffer is now taken in a method without loops and passed to a NoInlining local function that
has them, so both start at Tier0 as before.

Profiler, first use of 20 BCL enums (stages 1-4), 21 processes pinned to P cores, two alternating runs:
  JIT time:   v2.1.0 28.4 / 28.9 ms, before 32.4 ms, after 30.2 / 30.8 ms
  total time: v2.1.0 31.7 / 32.2 ms, before ~37 ms,  after 34.0 / 34.7 ms
  retained:   v2.1.0 256.6 KB, after 254.6 KB

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The other scenarios measure a few hand-picked enums (Fruits, HttpStatusCode, DayOfWeek, ConsoleKey),
so a change of the lookup tables can look better or worse than it is. Corpus goes through the first
512 public enums of the System.* / Microsoft.Win32.* assemblies of the shared framework (by name)
with 64 inputs each, so that every enum weighs the same; each scenario is one benchmark whose result
is the mean time of one operation over the whole corpus.

Inputs per enum: its names (Hit), lower case (IgnoreCase), its names with the middle character
replaced by another letter (Typo), names of other enums (Foreign), and its values (GetName / ToString).
Each enum is called through a delegate to a generic method created in the setup; the call costs the
same for every version and is spread over 64 inputs. The setup prints the corpus checksum to the log,
so that a comparison can check that every job measured the same corpus.

v2.1.0 vs this branch, one run on P cores (FASTENUM_BENCH_BASELINE, 3:21):
  TryParse_Hit         3.19 -> 2.79 ns  0.88
  TryParse_IgnoreCase  6.51 -> 5.40 ns  0.83
  TryParse_Typo        5.29 -> 2.81 ns  0.53
  TryParse_Foreign     8.45 -> 6.26 ns  0.74
  GetName              0.875 -> 0.870 ns  0.99
  ToString             0.865 -> 0.849 ns  0.98

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ColdCorpus takes the same 512 BCL enums as Corpus and measures the first GetName / TryParse /
TryParse(ignoreCase) of each, and all three in a row. A job mutator turns every job into a cold
start (RunStrategy.ColdStart, 15 launches, one iteration of one invocation, no warmup), so each
measurement is a new process and covers reflection, building the tables and JIT. The jobs of a
comparison keep their builds, so v2.1.0 and this branch are measured in one run. The setup does
not call into FastEnum nor Enum.GetNames(), so that it warms up nothing FastEnum would do itself.

The log shows only WorkloadActual / WorkloadExtra / WorkloadResult, no jitting invocation before
the measurement. Allocated comes from the extra iteration after the cold one, so it is not the
memory of the first use.

v2.1.0 vs this branch, one run on P cores (2:22), 15 processes each, StdDev about 3.5 ms:
  Cold_GetName             457.1 -> 445.1 ms  0.97
  Cold_TryParse            408.7 -> 424.5 ms  1.04
  Cold_TryParseIgnoreCase  401.4 -> 415.7 ms  1.04
  Cold_All                 510.0 -> 546.9 ms  1.07  (+72 us per enum)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@xin9le xin9le self-assigned this Nov 27, 2026
@xin9le xin9le added the enhancement New feature or request label Nov 27, 2026
@xin9le

xin9le commented Nov 27, 2026

Copy link
Copy Markdown
Owner

@lsoft
Thank you very much for this pull request! I sincerely appreciate you taking the time to work on it.

I've taken a quick look through the changes, and they are full of excellent insights. For example, your proposals include:

  • Improvements I had identified as tasks while implementing v2.1.0, but had forgotten to address
  • Ideas I've already started working on in my local environment for the next version
  • Fresh insights that made me think, "Ah, so there was still that approach!"

However, this pull request is quite large, which makes it difficult to review and merge as a whole. Please don't take this as a rejection of your proposals. Quite the opposite, I'd like to capture the core of your ideas, consider each one carefully, and incorporate them step by step.

I'd like to keep this pull request open until I've fully understood each change and finished incorporating them.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants