Repository navigation
Conversation
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>
Owner
|
@lsoft I've taken a quick look through the changes, and they are full of excellent insights. For example, your proposals include:
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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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:
NonConstantInputscenarios that the commits below are measured with.(len << 16) ^ (first << 8) ^ (mid << 4) ^ last, which for small tables is only the last character (allDayOfWeeknames 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.TryParse("123")andToString()of an undefined value through a booster no longer run theEnumInfo<T>static constructor just to read the type code.FrozenDictionary<int, string?>per member is replaced by astring?[](sparse indexes fall back to a small pair array). Same lookup speed, less memory at the firstGetLabel().EnumInfo<T>static constructor. An app that only formats values never builds them. Tier1 code still reads them as constants.TryParse(ignoreCase: true)againstEnum.TryParse.GeneratorAttributeSyntaxContext, which never equals the previous run, so every edit in the IDE regenerated every booster. Now it returns equatable records. Diagnostics keep their originalLocation, so#pragma warning disableand.editorconfigstill apply to FE0001–FE0004. The generated code is byte-for-byte the same.run-benchmarks.batpins BenchmarkDotNet to the P cores of a hybrid CPU. Without it, two runs of the same code differed by 10–15%.FASTENUM_BENCH_BASELINE=<other tree>\src\libsadds a baseline job built against another FastEnum source tree, so both versions run back to back in one run and get aRatiocolumn.ArrayPool<int>.Sharedmade the pool keep per-core stacks (25 KB for the process). Buffers up to 2 KB now come from the stack.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.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:
Hand-picked enums (
NonConstantInput)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.
GetName), memory retainedGetLabel()over 64 members with two labels eachBooster generator
The IDE case was measured with
CSharpGeneratorDriveron 50 boosters of 50 members, editing one file 40 times:Trade-offs
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.ColdCorpus, 15 fresh processes each, StdDev about 3.5 ms): the firstTryParsetakes +4% (about +30 µs per enum), and all three operations in a row take +7% (+72 µs per enum).GetNametakes −3%.nullcheck replaced a JIT constant, so it is not included.charorboolunderlying type can be declared in IL, though not in C#. With such an enum, every call still throwsTypeInitializationException, as before. The exception now namesTypeCodeOf<T>(commit 4), or the lazy table classes (commit 6), instead ofEnumInfo<T>.How it was tested
Correctness
FastEnum.UnitTestson net10.0 and net11.0. That is 635 tests up to commit 6 and 641 from commit 7, which adds the booster tests.IgnoreCaseEnumgets 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 withEnum.TryParse;Generators/IgnoreCaseTestsdoes the same for a generated booster;AnnotationTestscovers sparse label indexes (-1, 100) and undefined indexes.DOTNET_EnableAVX2=0, which runs the 128-bit path.#pragma warning disableor with.editorconfig, the same as with v2.1.0.char/boolenums in commit 4;Performance
CorpusandColdCorpus(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.GC.GetAllocatedBytesForCurrentThread();GC.GetTotalMemory(true);System.Runtime.JitInfo;Dropped after measuring
Member<T>(UTF-8 name,EnumMemberAttribute, labels) into a side object created on first access, to makeMember<T>smaller:GetEnumMemberValuewas 20% slower.To reproduce the comparison:
This work was done with Claude Code, and the commits carry a
Co-Authored-Bytrailer. Every change was reviewed and measured as described above. Thanks again for the library and for maintaining it!🤖 Generated with Claude Code