diff --git a/.gitattributes b/.gitattributes index eba1110b..3137f9ee 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,6 @@ # Auto detect text files and perform LF normalization -* text=auto \ No newline at end of file +* text=auto + +# cmd.exe may fail to find a label for goto / call in a batch file with LF line endings +*.bat text eol=crlf +*.ps1 text eol=crlf \ No newline at end of file diff --git a/eng/get-pcore-affinity.ps1 b/eng/get-pcore-affinity.ps1 new file mode 100644 index 00000000..aee34952 --- /dev/null +++ b/eng/get-pcore-affinity.ps1 @@ -0,0 +1,236 @@ +<# +.SYNOPSIS + Prints the affinity mask that keeps only the performance cores. + +.DESCRIPTION + Used by run-benchmarks.bat. On a hybrid CPU (Intel P/E cores, Snapdragon X, + Zen 5c) the scheduler may move a benchmark from a P core to an E core in the + middle of an iteration. That is not noise within StdDev but a several-fold + difference, and the mean of a whole run shifts with the share of time spent + on E cores. BenchmarkDotNet does not reject such a run; it only shows a + spread, and two runs of the same code disagree by 10-15%. + + The cores come from GetLogicalProcessorInformationEx(RelationProcessorCore): + every physical core carries an EfficiencyClass. A higher class means a more + performant core, and the class is non-zero ONLY on hybrid machines. So: + + * all cores of one class (a usual Xeon, Ryzen, any pre-hybrid Intel) - + nothing to restrict, the script prints nothing; + * several classes - the mask has every logical processor of the cores of + the highest class, SMT siblings included: the benchmarks are single + threaded, and an idle sibling does not disturb them. + + A mask belongs to a processor group (KAFFINITY) and a process lives in one + group, so on machines with more than 64 logical processors only group 0 is + taken; if it has no P cores, the script prints nothing again. + + Diagnostics go to stderr, in ASCII. stdout gets exactly one line with the + mask, or nothing; the caller must treat empty output as "no restriction", + not as an error. + +.PARAMETER AsDecimal + Print the mask as a decimal number instead of hexadecimal (start /affinity + takes hexadecimal). + +.OUTPUTS + System.String - the mask, or nothing. + +.EXAMPLE + PS> .\get-pcore-affinity.ps1 + 3C03 +#> +[CmdletBinding()] +param( + [switch] $AsDecimal +) + +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version Latest + +function Write-Diagnostic([string] $message) +{ + [Console]::Error.WriteLine($message) +} + +# The buffer is read by offsets rather than through a [StructLayout] class: +# SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX has a variable length (GroupMask is an +# ANYSIZE_ARRAY), which the marshaller cannot express. +# +# SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX { DWORD Relationship; DWORD Size; union {...} } +# PROCESSOR_RELATIONSHIP { BYTE Flags; BYTE EfficiencyClass; BYTE Reserved[20]; +# WORD GroupCount; GROUP_AFFINITY GroupMask[ANYSIZE_ARRAY]; } +# GROUP_AFFINITY { KAFFINITY Mask; WORD Group; WORD Reserved[3]; } +$source = @' +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.InteropServices; + +namespace FastEnumBench +{ + public struct CoreInfo + { + public byte EfficiencyClass; + public ushort Group; + public ulong Mask; + } + + public static class TopologyProbe + { + private const int RelationProcessorCore = 0; + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool GetLogicalProcessorInformationEx( + int relationshipType, IntPtr buffer, ref int returnedLength); + + public static CoreInfo[] GetCores() + { + int length = 0; + GetLogicalProcessorInformationEx(RelationProcessorCore, IntPtr.Zero, ref length); + if (length <= 0) + { + throw new Win32Exception(Marshal.GetLastWin32Error()); + } + + IntPtr buffer = Marshal.AllocHGlobal(length); + try + { + if (!GetLogicalProcessorInformationEx(RelationProcessorCore, buffer, ref length)) + { + throw new Win32Exception(Marshal.GetLastWin32Error()); + } + + // GROUP_AFFINITY: ULONG_PTR + WORD + WORD[3], so 16 bytes on x64 and 12 on x86. + int groupAffinitySize = IntPtr.Size + 8; + var cores = new List(); + + int offset = 0; + while (offset + 8 <= length) + { + int relationship = Marshal.ReadInt32(buffer, offset); + int size = Marshal.ReadInt32(buffer, offset + 4); + if (size <= 0) + { + break; + } + + if (relationship == RelationProcessorCore) + { + int processor = offset + 8; + byte efficiencyClass = Marshal.ReadByte(buffer, processor + 1); + int groupCount = (ushort)Marshal.ReadInt16(buffer, processor + 22); + + for (int i = 0; i < groupCount; i++) + { + int groupAffinity = processor + 24 + (i * groupAffinitySize); + ulong mask = IntPtr.Size == 8 + ? (ulong)Marshal.ReadInt64(buffer, groupAffinity) + : (ulong)(uint)Marshal.ReadInt32(buffer, groupAffinity); + + cores.Add(new CoreInfo + { + EfficiencyClass = efficiencyClass, + Group = (ushort)Marshal.ReadInt16(buffer, groupAffinity + IntPtr.Size), + Mask = mask + }); + } + } + + offset += size; + } + + return cores.ToArray(); + } + finally + { + Marshal.FreeHGlobal(buffer); + } + } + } +} +'@ + +function Get-BitCount([uint64] $mask) +{ + $count = 0 + while ($mask -ne 0) + { + $mask = $mask -band ($mask - 1) + $count++ + } + + return $count +} + +try +{ + if (-not ('FastEnumBench.TopologyProbe' -as [type])) + { + Add-Type -TypeDefinition $source -Language CSharp -ErrorAction Stop + } + + $cores = @([FastEnumBench.TopologyProbe]::GetCores()) +} +catch +{ + Write-Diagnostic ("P-core detection failed: " + $_.Exception.Message) + Write-Diagnostic "Falling back to the default affinity (all cores)." + exit 0 +} + +if ($cores.Count -eq 0) +{ + Write-Diagnostic "P-core detection: the OS reported no processor cores, using all cores." + exit 0 +} + +$classes = @($cores | ForEach-Object { [int] $_.EfficiencyClass } | Sort-Object -Unique) +if ($classes.Count -le 1) +{ + Write-Diagnostic ("P-core detection: uniform CPU, all " + $cores.Count + + " cores share efficiency class " + $classes[0] + " - no affinity mask needed.") + exit 0 +} + +$topClass = $classes[-1] +$fast = @($cores | Where-Object { [int] $_.EfficiencyClass -eq $topClass -and $_.Group -eq 0 }) +if ($fast.Count -eq 0) +{ + Write-Diagnostic ("P-core detection: processor group 0 has no cores of the fastest class " + + $topClass + " - a mask would only narrow the run, using all cores.") + exit 0 +} + +$mask = [uint64] 0 +foreach ($core in $fast) +{ + $mask = $mask -bor $core.Mask +} + +if ($mask -eq 0) +{ + Write-Diagnostic "P-core detection: the fastest cores carry an empty affinity mask, using all cores." + exit 0 +} + +$groupZeroTotal = 0 +foreach ($core in $cores) +{ + if ($core.Group -eq 0) + { + $groupZeroTotal += Get-BitCount $core.Mask + } +} + +Write-Diagnostic ("P-core detection: hybrid CPU, efficiency classes " + ($classes -join ',') + + "; " + $fast.Count + " core(s) of class " + $topClass + " -> " + (Get-BitCount $mask) + + " of " + $groupZeroTotal + " logical CPUs in group 0.") + +if ($AsDecimal) +{ + Write-Output ([string] $mask) +} +else +{ + Write-Output ('{0:X}' -f $mask) +} diff --git a/run-benchmarks.bat b/run-benchmarks.bat new file mode 100644 index 00000000..9f473fa8 --- /dev/null +++ b/run-benchmarks.bat @@ -0,0 +1,146 @@ +@echo off +rem --------------------------------------------------------------------------- +rem Runs the FastEnum benchmarks pinned to the performance cores and prints +rem the result tables only. +rem +rem Everything dotnet build and BenchmarkDotNet print - package restore, the +rem generated exe per job, per-iteration progress - goes to the log file. The +rem console gets only the markdown tables BenchmarkDotNet exports as +rem *-report-github.md. +rem +rem Arguments are passed to BenchmarkDotNet as they are; with none it runs +rem every benchmark (--filter *). +rem +rem run-benchmarks.bat - all benchmarks +rem run-benchmarks.bat --filter *NonConstantInput* - one class +rem +rem On a hybrid CPU the run is pinned to the performance cores - see the +rem affinity block below and eng\get-pcore-affinity.ps1. +rem +rem ASCII only on purpose: cmd.exe reads batch files in the OEM codepage, so +rem non-ASCII comments here would be mangled into unparsable commands. +rem --------------------------------------------------------------------------- + +setlocal + +cd /d "%~dp0" + +set "PROJECT=src\insights\FastEnum.Benchmarks\FastEnum.Benchmarks.csproj" +set "HOSTEXE=src\artifacts\bin\FastEnum.Benchmarks\release_net11.0\FastEnum.Benchmarks.exe" +set "ARTIFACTS=%CD%\BenchmarkDotNet.Artifacts" +set "LOG=%CD%\benchmarks.log" + +set "BENCHARGS=%*" +if not defined BENCHARGS set "BENCHARGS=--filter *" + +rem Remembered now, restored after the reports are printed - see :restorecp. +rem Split on the colon only and trim afterwards: chcp's message is localized and +rem its wording contains spaces, so a space delimiter would pick up a word. +for /f "tokens=2 delims=:" %%C in ('chcp') do for /f "tokens=*" %%D in ("%%C") do set "OLDCP=%%D" + +rem Report file names are derived from class names, so a stale report left by a +rem renamed benchmark would be printed below as if it came from this run. +if exist "%ARTIFACTS%" rd /s /q "%ARTIFACTS%" +if exist "%LOG%" del /q "%LOG%" + +rem A hybrid CPU (Intel P/E cores, Snapdragon X, Zen 5c) lets the scheduler move +rem a benchmark from a P core to an E core in the middle of an iteration, and that +rem is a several-fold difference, not noise within StdDev - BenchmarkDotNet only +rem reports it as a spread, and two runs of the same code disagree by 10-15%. +rem eng\get-pcore-affinity.ps1 asks Windows for the efficiency class of every +rem physical core and prints the mask of the fastest ones; on a CPU whose cores +rem are all equal it prints nothing and the run stays unrestricted. Its own +rem diagnostics go to the log. +rem +rem Set FASTENUM_BENCH_AFFINITY to a hex mask to pin the run by hand, or to +rem "off" to run on every core. +set "AFFINITY=" +if defined FASTENUM_BENCH_AFFINITY ( + if /i not "%FASTENUM_BENCH_AFFINITY%"=="off" set "AFFINITY=%FASTENUM_BENCH_AFFINITY%" +) else ( + for /f "usebackq tokens=1" %%M in (`powershell -NoLogo -NoProfile -ExecutionPolicy Bypass -File "%~dp0eng\get-pcore-affinity.ps1" 2^>^>"%LOG%"`) do set "AFFINITY=%%M" +) + +rem Whatever powershell.exe writes to stdout ends up here, and that is not always +rem the mask: a missing script file, for one, makes it print its logo instead. A +rem non-mask would be handed to start below, which would refuse to launch anything. +if defined AFFINITY call :checkmask + +if defined AFFINITY ( + echo Affinity: 0x%AFFINITY% - the run is pinned to these CPUs. +) else ( + echo Affinity: not restricted. +) + +echo [1/2] Building Release: %PROJECT% ... +dotnet build -c Release -f net11.0 "%PROJECT%" --nologo -v quiet >> "%LOG%" 2>&1 +if errorlevel 1 goto :failed + +rem The mask goes onto the host process rather than into BenchmarkDotNet's own +rem --affinity, for two reasons. Windows hands a process affinity down to every +rem child it starts, so the one mask covers the per-job exe BenchmarkDotNet +rem generates, builds and runs - and it is in place BEFORE the runtime of those +rem children starts, so the GC sizes its heaps for the cores they will actually +rem get. --affinity is applied to an already running process and is parsed as a +rem signed 32-bit number, so it cannot even express cores above CPU 30. +rem +rem Priority goes on for the same reason and by the same mechanism. Above normal +rem rather than high on purpose - high starves the shell that has to collect the +rem output, and the point is to lose fewer timeslices to background work. +rem +rem /b keeps the child in this console, so the redirection below still reaches it, +rem and /wait is what makes errorlevel below mean the benchmark run. +if defined AFFINITY ( + echo [2/2] Running benchmarks on the performance cores, above normal priority ... + start "FastEnum benchmarks" /affinity %AFFINITY% /abovenormal /b /wait "%HOSTEXE%" %BENCHARGS% >> "%LOG%" 2>&1 +) else ( + echo [2/2] Running benchmarks, above normal priority ... + start "FastEnum benchmarks" /abovenormal /b /wait "%HOSTEXE%" %BENCHARGS% >> "%LOG%" 2>&1 +) +if errorlevel 1 goto :failed + +if not exist "%ARTIFACTS%\results\*-report-github.md" goto :noresults + +rem Not "type": the reports are UTF-8 and contain the micro sign, which the OEM +rem codepage turns into mojibake. They are also HTML-escaped by BenchmarkDotNet's +rem github exporter. PowerShell reads them as UTF-8 and unescapes; chcp makes the +rem console show it. +chcp 65001 > nul +powershell -NoProfile -Command "[Console]::OutputEncoding = [Text.Encoding]::UTF8; Get-ChildItem '%ARTIFACTS%\results' -Filter '*-report-github.md' | ForEach-Object { Write-Output ''; Write-Output ('=' * 79); Write-Output (' ' + $_.BaseName); Write-Output ('=' * 79); Write-Output ([System.Net.WebUtility]::HtmlDecode((Get-Content -Raw -Encoding UTF8 $_.FullName))) }" +call :restorecp + +echo Full log: %LOG% +endlocal +exit /b 0 + +rem The console codepage is process-wide and survives this script, so put back +rem whatever the user had before. +:restorecp +if defined OLDCP chcp %OLDCP% > nul +goto :eof + +rem No space before the pipe: it would be echoed as part of the mask. +:checkmask +if /i "%AFFINITY:~0,2%"=="0x" set "AFFINITY=%AFFINITY:~2%" +echo %AFFINITY%| findstr /r /i /c:"^[0-9a-f][0-9a-f]*$" > nul +if errorlevel 1 ( + echo Affinity: "%AFFINITY%" is not a hex mask, ignoring it. + set "AFFINITY=" +) +goto :eof + +:noresults +echo. +echo No report files were produced. Full log: %LOG% +endlocal +exit /b 1 + +:failed +echo. +echo BUILD OR RUN FAILED. Log tail: +echo ------------------------------------------------------------------------------- +powershell -NoProfile -Command "Get-Content -Tail 40 '%LOG%'" +echo ------------------------------------------------------------------------------- +echo Full log: %LOG% +endlocal +exit /b 1 diff --git a/src/insights/FastEnum.Benchmarks/FastEnum.Benchmarks.csproj b/src/insights/FastEnum.Benchmarks/FastEnum.Benchmarks.csproj index 2b465cfc..bb56702a 100644 --- a/src/insights/FastEnum.Benchmarks/FastEnum.Benchmarks.csproj +++ b/src/insights/FastEnum.Benchmarks/FastEnum.Benchmarks.csproj @@ -11,9 +11,18 @@ + + + $(MSBuildThisFileDirectory)..\..\libs + + - - + + Analyzer false diff --git a/src/insights/FastEnum.Benchmarks/Internals/BenchmarkConfig.cs b/src/insights/FastEnum.Benchmarks/Internals/BenchmarkConfig.cs index 1357dd24..7fd6ed52 100644 --- a/src/insights/FastEnum.Benchmarks/Internals/BenchmarkConfig.cs +++ b/src/insights/FastEnum.Benchmarks/Internals/BenchmarkConfig.cs @@ -18,6 +18,39 @@ public static IConfig ForShortRun() => CreateSharedConfig(Job.ShortRun); + /// + /// Compares this source tree with another one (e.g. a worktree of the previous release) in one run. + /// + /// The 'src/libs' directory of the baseline tree. + /// + /// Numbers of two separate runs drift by 10-15% on their own, so a comparison between them is not trustworthy. + /// Here every benchmark is measured with both versions back to back, each in its own process built against its own FastEnum.Core. + /// Two launches per job average out the placement of code and data, which is fixed for a process. + /// The iterations are shorter than Job.Default to keep a comparison of a dozen benchmarks at about 5 minutes. + /// + public static IConfig ForComparison(string baselineLibs) + { + var job = Job.Default + .WithRuntime(CoreRuntime.Core11_0) + .WithLaunchCount(2) + .WithWarmupCount(5) + .WithIterationCount(10) + .WithIterationTime(Perfolizer.Horology.TimeInterval.FromMilliseconds(200)); + var baseline = job + .WithArguments([new MsBuildArgument($"/p:FastEnumLibs=\"{baselineLibs.TrimEnd('\\', '/')}\"")]) // quoted: the path may contain spaces + .WithId("baseline") + .AsBaseline(); + var current = job.WithId("current"); + + return ManualConfig + .CreateMinimumViable() + .AddExporter(MarkdownExporter.GitHub) + .AddDiagnoser(MemoryDiagnoser.Default) + .AddJob(baseline) + .AddJob(current); + } + + #region Helpers private static ManualConfig CreateSharedConfig(Job job) { diff --git a/src/insights/FastEnum.Benchmarks/Models/Boosters.cs b/src/insights/FastEnum.Benchmarks/Models/Boosters.cs index 8e07590d..36a38c23 100644 --- a/src/insights/FastEnum.Benchmarks/Models/Boosters.cs +++ b/src/insights/FastEnum.Benchmarks/Models/Boosters.cs @@ -5,3 +5,15 @@ [FastEnum] public sealed partial class FruitsBooster { } + + + +[FastEnum] +public sealed partial class HttpStatusCodeBooster +{ } + + + +[FastEnum] +public sealed partial class ConsoleKeyBooster +{ } diff --git a/src/insights/FastEnum.Benchmarks/Models/Enums.cs b/src/insights/FastEnum.Benchmarks/Models/Enums.cs index 28449651..0a0396f8 100644 --- a/src/insights/FastEnum.Benchmarks/Models/Enums.cs +++ b/src/insights/FastEnum.Benchmarks/Models/Enums.cs @@ -6,6 +6,31 @@ namespace FastEnumUtility.Benchmarks.Models; +/// +/// Enum whose members have labels. +/// +public enum Colors +{ + [Label("red"), Label("#FF0000", 1)] + Red, + [Label("green"), Label("#00FF00", 1)] + Green, + [Label("blue"), Label("#0000FF", 1)] + Blue, + [Label("cyan"), Label("#00FFFF", 1)] + Cyan, + [Label("magenta"), Label("#FF00FF", 1)] + Magenta, + [Label("yellow"), Label("#FFFF00", 1)] + Yellow, + [Label("black"), Label("#000000", 1)] + Black, + [Label("white"), Label("#FFFFFF", 1)] + White, +} + + + [EnumExtensions] public enum Fruits : byte { diff --git a/src/insights/FastEnum.Benchmarks/Program.cs b/src/insights/FastEnum.Benchmarks/Program.cs index e3f72283..d1191ea5 100644 --- a/src/insights/FastEnum.Benchmarks/Program.cs +++ b/src/insights/FastEnum.Benchmarks/Program.cs @@ -4,11 +4,19 @@ -var config = BenchmarkConfig.ForDefault(); +// note: +// - FASTENUM_BENCH_BASELINE = the 'src/libs' directory of another tree compares it with this one in one run; see BenchmarkConfig.ForComparison(). +var baselineLibs = System.Environment.GetEnvironmentVariable("FASTENUM_BENCH_BASELINE"); +var config = string.IsNullOrEmpty(baselineLibs) + ? BenchmarkConfig.ForDefault() + : BenchmarkConfig.ForComparison(baselineLibs); //var config = BenchmarkConfig.ForShortRun(); var switcher = new BenchmarkSwitcher( [ + typeof(ColdCorpus), + typeof(Corpus), typeof(EnumMemberAttribute), + typeof(EqualsIgnoreCaseByLength), typeof(GetName), typeof(GetNames), typeof(GetValues), diff --git a/src/insights/FastEnum.Benchmarks/Scenarios/ColdCorpus.cs b/src/insights/FastEnum.Benchmarks/Scenarios/ColdCorpus.cs new file mode 100644 index 00000000..06aa0f3b --- /dev/null +++ b/src/insights/FastEnum.Benchmarks/Scenarios/ColdCorpus.cs @@ -0,0 +1,173 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Runtime.Loader; +using BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Engines; +using BenchmarkDotNet.Jobs; + +namespace FastEnumUtility.Benchmarks.Scenarios; + + + +/// +/// The first use of FastEnum for each enum of the corpus, in a fresh process every time. +/// +/// +/// +/// The same 512 BCL enums as . Every launch is a new process with one iteration of one invocation and no warmup +/// (see ), so a measurement covers everything the first use costs: +/// reflection over the fields, building the tables, and JIT of the generic code for every enum type. +/// +/// +/// The setup only finds the types and creates the delegates; it does not call them, nor touch the enums through Enum.GetNames() and the like, +/// so that it does not warm up anything FastEnum would do itself. +/// +/// +[ColdStart] +public class ColdCorpus +{ + #region Constants + private const int EnumCount = 512; + #endregion + + + #region Fields + private Action[] _getName = null!; + private Action[] _tryParse = null!; + private Action[] _tryParseIgnoreCase = null!; + #endregion + + + [GlobalSetup] + public void Setup() + { + var types = CollectEnums().Take(EnumCount).ToArray(); + if (types.Length != EnumCount) + throw new InvalidOperationException($"The corpus has only {types.Length} enums; {EnumCount} are needed."); + + this._getName = create(nameof(GetNameOf)); + this._tryParse = create(nameof(TryParseOf)); + this._tryParseIgnoreCase = create(nameof(TryParseIgnoreCaseOf)); + + // note: + // - Printed into the log, so that a comparison can check every job measured the same corpus. + var checksum = 2166136261u; + foreach (var c in types.SelectMany(static t => t.FullName + ";")) + checksum = (checksum ^ c) * 16777619u; + Console.WriteLine($"// ColdCorpus: {types.Length} enums, {types[0].FullName} .. {types[^1].FullName}, checksum {checksum:X8}"); + + + #region Local Functions + Action[] create(string name) + { + var method = typeof(ColdCorpus).GetMethod(name, BindingFlags.NonPublic | BindingFlags.Static)!; + return types.Select(t => method.MakeGenericMethod(t).CreateDelegate()).ToArray(); + } + #endregion + } + + + #region Benchmarks + [Benchmark] + public void Cold_GetName() + => Run(this._getName); + + + [Benchmark] + public void Cold_TryParse() + => Run(this._tryParse); + + + [Benchmark] + public void Cold_TryParseIgnoreCase() + => Run(this._tryParseIgnoreCase); + + + [Benchmark] + public void Cold_All() + { + Run(this._getName); + Run(this._tryParse); + Run(this._tryParseIgnoreCase); + } + #endregion + + + #region Helpers + private static object? s_sink; + + + private static void Run(Action[] actions) + { + foreach (var x in actions) + x(); + } + + + private static void GetNameOf() + where T : struct, Enum + => s_sink = FastEnum.GetName(default(T)); + + + private static void TryParseOf() + where T : struct, Enum + { + _ = FastEnum.TryParse("Zzz", out var result); + s_sink = result; + } + + + private static void TryParseIgnoreCaseOf() + where T : struct, Enum + { + _ = FastEnum.TryParse("zzz", ignoreCase: true, out var result); + s_sink = result; + } + + + private static List CollectEnums() + { + // note: + // - The same selection as Corpus, without Enum.GetNames() (it would warm up the runtime's own enum cache that FastEnum uses). + var paths = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!).Split(System.IO.Path.PathSeparator); + var result = new HashSet(); + foreach (var path in paths) + { + var file = System.IO.Path.GetFileName(path); + if (!file.StartsWith("System.", StringComparison.Ordinal) && !file.StartsWith("Microsoft.Win32.", StringComparison.Ordinal)) + continue; + try + { + var assembly = AssemblyLoadContext.Default.LoadFromAssemblyName(AssemblyName.GetAssemblyName(path)); + foreach (var type in assembly.GetExportedTypes()) + { + if (type.IsEnum && !type.ContainsGenericParameters) + result.Add(type); + } + } + catch + { + // not loadable on this platform; skip + } + } + return [.. result.OrderBy(static t => t.FullName, StringComparer.Ordinal)]; + } + #endregion + + + + /// + /// Turns every job into a cold start: a new process per measurement, one iteration of one invocation, no warmup. + /// + /// It mutates the jobs of the config, so the baseline / current jobs of a comparison keep their builds. + private sealed class ColdStartAttribute() + : JobMutatorConfigBaseAttribute(Job.Default + .WithStrategy(RunStrategy.ColdStart) + .WithLaunchCount(15) + .WithWarmupCount(0) + .WithIterationCount(1) + .WithInvocationCount(1) + .WithUnrollFactor(1)); +} diff --git a/src/insights/FastEnum.Benchmarks/Scenarios/Corpus.cs b/src/insights/FastEnum.Benchmarks/Scenarios/Corpus.cs new file mode 100644 index 00000000..c75d06fd --- /dev/null +++ b/src/insights/FastEnum.Benchmarks/Scenarios/Corpus.cs @@ -0,0 +1,276 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.Loader; +using BenchmarkDotNet.Attributes; + +namespace FastEnumUtility.Benchmarks.Scenarios; + + + +/// +/// Every scenario over a corpus of 512 public enums of the BCL, as one benchmark each. +/// +/// +/// +/// The other scenarios measure a few hand-picked enums, so a change of the lookup tables can look better or worse than it is. +/// Here each benchmark goes through all the enums of the corpus with 64 inputs each, so that every enum weighs the same, +/// and the result is the mean time of one operation over the whole corpus. +/// +/// +/// The enums are generic arguments known only at run time, so each one is called through a delegate to a generic method, +/// created once in the setup. The call costs the same for every version and is spread over the 64 inputs. +/// +/// +/// Inputs per enum: its names (Hit), the same in lower case (IgnoreCase), its names with one character in the middle replaced +/// by another letter (Typo; names of other enums if none of them is free), and names of other enums (Foreign). +/// GetName / ToString go through its defined values. +/// +/// +public class Corpus +{ + #region Constants + private const int EnumCount = 512; + private const int InputsPerEnum = 64; + private const int Operations = EnumCount * InputsPerEnum; + #endregion + + + #region Fields + private Func[] _tryParse = null!; + private Func[] _tryParseIgnoreCase = null!; + private Func[] _getName = null!; + private Func[] _toString = null!; + private object[] _hits = null!; + private object[] _lower = null!; + private object[] _typos = null!; + private object[] _foreign = null!; + private object[] _values = null!; + #endregion + + + [GlobalSetup] + public void Setup() + { + var all = CollectEnums(); + var pool = all.SelectMany(static t => Enum.GetNames(t)).Distinct().ToArray(); + var random = new Random(42); + + var chosen = new List(); + var tryParse = new List>(); + var tryParseIgnoreCase = new List>(); + var getName = new List>(); + var toString = new List>(); + var hits = new List(); + var lower = new List(); + var typos = new List(); + var foreign = new List(); + var values = new List(); + foreach (var type in all) + { + if (tryParse.Count == EnumCount) + break; + + try + { + var names = Enum.GetNames(type); + var defined = new HashSet(names, StringComparer.OrdinalIgnoreCase); + var shuffled = names.OrderBy(_ => random.Next()).ToArray(); + var foreignNames = pool.Where(x => !defined.Contains(x)).OrderBy(_ => random.Next()).Take(InputsPerEnum).ToArray(); + var typoNames = shuffled + .Select(static x => + { + var chars = x.ToCharArray(); + var i = chars.Length / 2; + var c = chars[i]; + chars[i] = char.IsAsciiLetterLower(c) ? (char)('a' + ((c - 'a' + 1) % 26)) + : char.IsAsciiLetterUpper(c) ? (char)('A' + ((c - 'A' + 1) % 26)) + : 'x'; + return new string(chars); + }) + .Where(x => !defined.Contains(x) && !char.IsAsciiDigit(x[0]) && x[0] is not '+' and not '-') + .ToArray(); + var definedValues = Enum.GetValues(type); + var cycledValues = Array.CreateInstance(type, InputsPerEnum); + for (var i = 0; i < InputsPerEnum; i++) + cycledValues.SetValue(definedValues.GetValue(i % definedValues.Length), i); + + var p = create(nameof(TryParseOf), type); + var pi = create(nameof(TryParseIgnoreCaseOf), type); + var g = create(nameof(GetNameOf), type); + var s = create(nameof(ToStringOf), type); + var hit = cycle(shuffled); + + // An enum FastEnum cannot handle is left out of the corpus. + _ = p(hit); + _ = g(cycledValues); + + chosen.Add(type); + tryParse.Add(p); + tryParseIgnoreCase.Add(pi); + getName.Add(g); + toString.Add(s); + hits.Add(hit); + lower.Add(hit.Select(static x => x.ToLowerInvariant()).ToArray()); + typos.Add(cycle(typoNames.Length > 0 ? typoNames : foreignNames)); + foreign.Add(cycle(foreignNames)); + values.Add(cycledValues); + } + catch + { + // not supported by FastEnum; skip + } + } + + if (tryParse.Count != EnumCount) + throw new InvalidOperationException($"The corpus has only {tryParse.Count} enums; {EnumCount} are needed."); + + // note: + // - Printed into the log, so that a comparison can check every job measured the same corpus. + // - FNV-1a over the type names and their member names; string.GetHashCode() is randomized per process. + var checksum = 2166136261u; + foreach (var c in chosen.SelectMany(static t => t.FullName + ":" + string.Join(",", Enum.GetNames(t)) + ";")) + checksum = (checksum ^ c) * 16777619u; + Console.WriteLine($"// Corpus: {chosen.Count} of {all.Count} enums, {chosen[0].FullName} .. {chosen[^1].FullName}, checksum {checksum:X8}"); + + this._tryParse = [.. tryParse]; + this._tryParseIgnoreCase = [.. tryParseIgnoreCase]; + this._getName = [.. getName]; + this._toString = [.. toString]; + this._hits = [.. hits]; + this._lower = [.. lower]; + this._typos = [.. typos]; + this._foreign = [.. foreign]; + this._values = [.. values]; + + + #region Local Functions + static Func create(string name, Type type) + => typeof(Corpus).GetMethod(name, BindingFlags.NonPublic | BindingFlags.Static)!.MakeGenericMethod(type).CreateDelegate>(); + + + static string[] cycle(string[] source) + => Enumerable.Range(0, InputsPerEnum).Select(i => source[i % source.Length]).ToArray(); + #endregion + } + + + #region Benchmarks + [Benchmark(OperationsPerInvoke = Operations)] + public long TryParse_Hit() + => Run(this._tryParse, this._hits); + + + [Benchmark(OperationsPerInvoke = Operations)] + public long TryParse_IgnoreCase() + => Run(this._tryParseIgnoreCase, this._lower); + + + [Benchmark(OperationsPerInvoke = Operations)] + public long TryParse_Typo() + => Run(this._tryParse, this._typos); + + + [Benchmark(OperationsPerInvoke = Operations)] + public long TryParse_Foreign() + => Run(this._tryParse, this._foreign); + + + [Benchmark(OperationsPerInvoke = Operations)] + public long GetName() + => Run(this._getName, this._values); + + + [Benchmark(OperationsPerInvoke = Operations)] + public long ToString_() + => Run(this._toString, this._values); + #endregion + + + #region Helpers + private static long Run(Func[] operations, object[] inputs) + { + long sum = 0; + for (var i = 0; i < operations.Length; i++) + sum += operations[i](inputs[i]); + return sum; + } + + + private static long TryParseOf(object inputs) + where T : struct, Enum + { + long sum = 0; + foreach (var x in (string[])inputs) + { + if (FastEnum.TryParse(x, out var result)) + sum += Unsafe.As(ref result) + 1; + } + return sum; + } + + + private static long TryParseIgnoreCaseOf(object inputs) + where T : struct, Enum + { + long sum = 0; + foreach (var x in (string[])inputs) + { + if (FastEnum.TryParse(x, ignoreCase: true, out var result)) + sum += Unsafe.As(ref result) + 1; + } + return sum; + } + + + private static long GetNameOf(object values) + where T : struct, Enum + { + long sum = 0; + foreach (var x in (T[])values) + sum += FastEnum.GetName(x)?.Length ?? 0; + return sum; + } + + + private static long ToStringOf(object values) + where T : struct, Enum + { + long sum = 0; + foreach (var x in (T[])values) + sum += FastEnum.ToString(x).Length; + return sum; + } + + + private static List CollectEnums() + { + // note: + // - Every public enum of the System.* / Microsoft.Win32.* assemblies of the shared framework, ordered by name, so the corpus is the same on every run. + var paths = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!).Split(System.IO.Path.PathSeparator); + var result = new HashSet(); + foreach (var path in paths) + { + var file = System.IO.Path.GetFileName(path); + if (!file.StartsWith("System.", StringComparison.Ordinal) && !file.StartsWith("Microsoft.Win32.", StringComparison.Ordinal)) + continue; + try + { + var assembly = AssemblyLoadContext.Default.LoadFromAssemblyName(AssemblyName.GetAssemblyName(path)); + foreach (var type in assembly.GetExportedTypes()) + { + if (type.IsEnum && !type.ContainsGenericParameters && Enum.GetNames(type).Length > 0) + result.Add(type); + } + } + catch + { + // not loadable on this platform; skip + } + } + return [.. result.OrderBy(static t => t.FullName, StringComparer.Ordinal)]; + } + #endregion +} diff --git a/src/insights/FastEnum.Benchmarks/Scenarios/EqualsIgnoreCaseByLength.cs b/src/insights/FastEnum.Benchmarks/Scenarios/EqualsIgnoreCaseByLength.cs new file mode 100644 index 00000000..7b92e3ae --- /dev/null +++ b/src/insights/FastEnum.Benchmarks/Scenarios/EqualsIgnoreCaseByLength.cs @@ -0,0 +1,41 @@ +using System; +using BenchmarkDotNet.Attributes; +using FastEnumUtility.Internals; + +namespace FastEnumUtility.Benchmarks.Scenarios; + + + +/// +/// Case-insensitive comparison of an ASCII name, used by the case-insensitive name lookup. +/// +public class EqualsIgnoreCaseByLength +{ + private string _ascii = null!; + private string _other = null!; + + + [Params(1, 2, 3, 6, 12, 17, 24, 32)] + public int Length { get; set; } + + + [GlobalSetup] + public void Setup() + { + var chars = new char[this.Length]; + for (var i = 0; i < chars.Length; i++) + chars[i] = (char)('A' + (i % 26)); + this._ascii = new string(chars); + this._other = this._ascii.ToLowerInvariant(); + } + + + [Benchmark(Baseline = true)] + public bool OrdinalIgnoreCase() + => MemoryExtensions.Equals(this._ascii, this._other, StringComparison.OrdinalIgnoreCase); + + + [Benchmark] + public bool EqualsAscii() + => StringHelper.CaseInsensitive.EqualsAscii(this._ascii, this._other); +} diff --git a/src/insights/FastEnum.Benchmarks/Scenarios/NonConstantInput.cs b/src/insights/FastEnum.Benchmarks/Scenarios/NonConstantInput.cs index 00607017..6c1f6606 100644 --- a/src/insights/FastEnum.Benchmarks/Scenarios/NonConstantInput.cs +++ b/src/insights/FastEnum.Benchmarks/Scenarios/NonConstantInput.cs @@ -26,6 +26,11 @@ public class NonConstantInput private string[] _continuousNamesUndefined = null!; private string[] _discontinuousNames = null!; private string[] _discontinuousNamesLower = null!; + private string[] _discontinuousNamesUndefined = null!; + private string[] _dayOfWeekNames = null!; + private string[] _dayOfWeekNamesLower = null!; + private string[] _consoleKeyNamesLower = null!; + private Colors[] _colors = null!; #endregion @@ -51,7 +56,15 @@ public void Setup() this._continuousNamesUndefined = this._continuousNames.Select(static x => $"{x}_").ToArray(); this._discontinuousNames = pick(random, Enum.GetNames()); this._discontinuousNamesLower = this._discontinuousNames.Select(static x => x.ToLowerInvariant()).ToArray(); - + this._discontinuousNamesUndefined = this._discontinuousNames.Select(static x => $"{x}_").ToArray(); + this._dayOfWeekNames = pick(random, Enum.GetNames()); + this._dayOfWeekNamesLower = this._dayOfWeekNames.Select(static x => x.ToLowerInvariant()).ToArray(); + this._consoleKeyNamesLower = pick(random, Enum.GetNames()).Select(static x => x.ToLowerInvariant()).ToArray(); // 1-18 chars + this._colors = pick(random, Enum.GetValues()); + + _ = FastEnum.GetMembers(); + _ = FastEnum.GetMembers(); + _ = FastEnum.GetMembers(); _ = FastEnum.GetMembers(); _ = FastEnum.GetMembers(); _ = FastEnum.GetMembers(); @@ -226,6 +239,26 @@ public int TryParse_Discontinuous() sum += FastEnum.TryParse(x, out var result) ? (int)result : 0; return sum; } + + + [Benchmark(OperationsPerInvoke = Count)] + public int TryParse_Discontinuous_Undefined() + { + var sum = 0; + foreach (var x in this._discontinuousNamesUndefined) + sum += FastEnum.TryParse(x, out var result) ? (int)result : 0; + return sum; + } + + + [Benchmark(OperationsPerInvoke = Count)] + public int TryParse_DayOfWeek() + { + var sum = 0; + foreach (var x in this._dayOfWeekNames) + sum += FastEnum.TryParse(x, out var result) ? (int)result : 0; + return sum; + } #endregion @@ -248,5 +281,89 @@ public int TryParseIgnoreCase_Discontinuous() sum += FastEnum.TryParse(x, ignoreCase: true, out var result) ? (int)result : 0; return sum; } + + + [Benchmark(OperationsPerInvoke = Count)] + public int TryParseIgnoreCase_DayOfWeek() + { + var sum = 0; + foreach (var x in this._dayOfWeekNamesLower) + sum += FastEnum.TryParse(x, ignoreCase: true, out var result) ? (int)result : 0; + return sum; + } + + + [Benchmark(OperationsPerInvoke = Count)] + public int TryParseIgnoreCase_ConsoleKey() + { + var sum = 0; + foreach (var x in this._consoleKeyNamesLower) + sum += FastEnum.TryParse(x, ignoreCase: true, out var result) ? (int)result : 0; + return sum; + } + #endregion + + + #region TryParse (source generator) + [Benchmark(OperationsPerInvoke = Count)] + public int Booster_TryParse_Discontinuous() + { + var sum = 0; + foreach (var x in this._discontinuousNames) + sum += FastEnum.TryParse(x, out var result) ? (int)result : 0; + return sum; + } + + + [Benchmark(OperationsPerInvoke = Count)] + public int Booster_TryParseIgnoreCase_Continuous() + { + var sum = 0; + foreach (var x in this._continuousNamesLower) + sum += FastEnum.TryParse(x, ignoreCase: true, out var result) ? (int)result : 0; + return sum; + } + + + [Benchmark(OperationsPerInvoke = Count)] + public int Booster_TryParseIgnoreCase_Discontinuous() + { + var sum = 0; + foreach (var x in this._discontinuousNamesLower) + sum += FastEnum.TryParse(x, ignoreCase: true, out var result) ? (int)result : 0; + return sum; + } + + + [Benchmark(OperationsPerInvoke = Count)] + public int Booster_TryParseIgnoreCase_ConsoleKey() + { + var sum = 0; + foreach (var x in this._consoleKeyNamesLower) + sum += FastEnum.TryParse(x, ignoreCase: true, out var result) ? (int)result : 0; + return sum; + } + #endregion + + + #region Attributes + [Benchmark(OperationsPerInvoke = Count)] + public int GetLabel() + { + var sum = 0; + foreach (var x in this._colors) + sum += x.GetLabel(0)!.Length + x.GetLabel(1)!.Length; + return sum; + } + + + [Benchmark(OperationsPerInvoke = Count)] + public int GetEnumMemberValue() + { + var sum = 0; + foreach (var x in this._continuous) + sum += x.GetEnumMemberValue(throwIfNotFound: false)?.Length ?? 0; + return sum; + } #endregion } diff --git a/src/insights/FastEnum.UnitTests/Cases/Generators/IgnoreCaseTests.cs b/src/insights/FastEnum.UnitTests/Cases/Generators/IgnoreCaseTests.cs new file mode 100644 index 00000000..16ba0aaf --- /dev/null +++ b/src/insights/FastEnum.UnitTests/Cases/Generators/IgnoreCaseTests.cs @@ -0,0 +1,134 @@ +using System; +using System.Threading.Tasks; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Shouldly; +using TBooster = FastEnumUtility.UnitTests.Models.IgnoreCaseEnumBooster; +using TEnum = FastEnumUtility.UnitTests.Models.IgnoreCaseEnum; + +namespace FastEnumUtility.UnitTests.Cases.Generators; + + + +[TestClass] +public sealed class IgnoreCaseTests +{ + // note: + // - The generated case-insensitive parsing has its own code path (a switch on the length, then a comparison of the whole name), apart from the reflection path. + // - These tests prove that it is fully compatible with System.Enum, which compares names by OrdinalIgnoreCase. + + private static readonly string[] s_names = Enum.GetNames(); + + + [TestMethod] + public void AsIs() + { + foreach (var name in s_names) + AssertCompatibility(name); + } + + + [TestMethod] + public void UpperCase() + { + foreach (var name in s_names) + AssertCompatibility(name.ToUpperInvariant()); + } + + + [TestMethod] + public void LowerCase() + { + foreach (var name in s_names) + AssertCompatibility(name.ToLowerInvariant()); + } + + + [TestMethod] + public void Longer() + { + foreach (var name in s_names) + { + AssertCompatibility($"{name}x"); + AssertCompatibility($"x{name}"); + } + } + + + [TestMethod] + public void Shorter() + { + foreach (var name in s_names) + { + AssertCompatibility(name.AsSpan()[1..]); + AssertCompatibility(name.AsSpan()[..^1]); + } + } + + + [TestMethod] + public void ReplaceWithEveryCharacter() + { + // note: + // - Replaces each character of each name with every UTF-16 code unit. + // - This covers the case flipping of ASCII letters, non-letters that differ from a letter or another character only in bit 0x20 (e.g. '@' and '`' / '_' and DEL), + // and non-ASCII characters whose upper case is ASCII (e.g. U+017F). + + Parallel.ForEach(s_names, static name => + { + var chars = name.ToCharArray(); + for (var i = 0; i < chars.Length; i++) + { + for (int c = char.MinValue; c <= char.MaxValue; c++) + { + chars[i] = (char)c; + if (isComparable(chars)) + AssertCompatibility(chars); + } + chars[i] = name[i]; + } + }); + + + #region Local Functions + static bool isComparable(ReadOnlySpan text) + { + // note: + // - Excludes the inputs for which System.Enum intentionally behaves differently from FastEnum; they are out of scope here. + // - System.Enum trims white spaces. + // - System.Enum splits by comma to parse flags. + // - Numeric value parsing. + + if (text.IsEmpty) + return false; + + var first = text[0]; + var last = text[^1]; + if (char.IsWhiteSpace(first) || char.IsWhiteSpace(last)) + return false; + + if (text.Contains(',')) + return false; + + if (first is '+' or '-') + return false; + + if (char.IsAsciiDigit(first)) + return false; + + return true; + } + #endregion + } + + + #region Helpers + private static void AssertCompatibility(ReadOnlySpan text) + { + const bool ignoreCase = true; + var expect = Enum.TryParse(text, ignoreCase, out var expectValue); + var actual = FastEnum.TryParse(text, ignoreCase, out var actualValue); + actual.ShouldBe(expect); + actualValue.ShouldBe(expectValue); + } + #endregion +} diff --git a/src/insights/FastEnum.UnitTests/Cases/Reflections/AnnotationTests.cs b/src/insights/FastEnum.UnitTests/Cases/Reflections/AnnotationTests.cs index 47357c23..7cc0264b 100644 --- a/src/insights/FastEnum.UnitTests/Cases/Reflections/AnnotationTests.cs +++ b/src/insights/FastEnum.UnitTests/Cases/Reflections/AnnotationTests.cs @@ -75,6 +75,17 @@ public void GetLabel() TEnum.Four.GetLabel(2, throwIfNotFound: false).ShouldBeNull(); TEnum.Four.GetLabel(2, throwIfNotFound: true).ShouldBeNull(); + TEnum.Four.GetLabel(0, throwIfNotFound: false).ShouldBeNull(); + Should.Throw(static () => TEnum.Four.GetLabel(0, throwIfNotFound: true)); + Should.Throw(static () => TEnum.Four.GetLabel(3, throwIfNotFound: true)); + Should.Throw(static () => TEnum.Four.GetLabel(-1, throwIfNotFound: true)); + + TEnum.Eight.GetLabel(-1, throwIfNotFound: true).ShouldBe("負"); + TEnum.Eight.GetLabel(100, throwIfNotFound: true).ShouldBe("百"); + TEnum.Eight.GetLabel(3, throwIfNotFound: true).ShouldBeNull(); + TEnum.Eight.GetLabel(0, throwIfNotFound: false).ShouldBeNull(); + Should.Throw(static () => TEnum.Eight.GetLabel(0, throwIfNotFound: true)); + Should.Throw(static () => TEnum.Eight.GetLabel(99, throwIfNotFound: true)); const TEnum undefined = (TEnum)123; undefined.GetLabel(0, throwIfNotFound: false).ShouldBeNull(); diff --git a/src/insights/FastEnum.UnitTests/Models/Boosters.cs b/src/insights/FastEnum.UnitTests/Models/Boosters.cs index e20be977..a304a22a 100644 --- a/src/insights/FastEnum.UnitTests/Models/Boosters.cs +++ b/src/insights/FastEnum.UnitTests/Models/Boosters.cs @@ -71,3 +71,9 @@ public sealed partial class EmptyEnumBooster [FastEnum] public sealed partial class CaseInsensitiveEnumBooster { } + + + +[FastEnum] +public sealed partial class IgnoreCaseEnumBooster +{ } diff --git a/src/insights/FastEnum.UnitTests/Models/Enums.cs b/src/insights/FastEnum.UnitTests/Models/Enums.cs index c6e4e797..787d680a 100644 --- a/src/insights/FastEnum.UnitTests/Models/Enums.cs +++ b/src/insights/FastEnum.UnitTests/Models/Enums.cs @@ -234,6 +234,12 @@ public enum AnnotationEnum [Label(null, 2)] Four = 4, + + // sparse indexes + [Label("負", -1)] + [Label("百", 100)] + [Label(null, 3)] + Eight = 8, } @@ -293,6 +299,9 @@ public enum IgnoreCaseEnum Abcdefghijklmno, // 15 Abcdefghijklmnop, // 16 Abcdefghijklmnopq, // 17 + Abcdefghijklmnopqrstuvwx, // 24 + Abcdefghijklmnopqrstuvwxyz_01234, // 32 + Abcdefghijklmnopqrstuvwxyz_012345, // 33 Abcdefghijklmnopqrstuvwxyz_0123456789, // ASCII only : digit / underscore / all upper / all lower diff --git a/src/libs/FastEnum.Core/FastEnum.cs b/src/libs/FastEnum.Core/FastEnum.cs index 81c3be4c..ae3c80d2 100644 --- a/src/libs/FastEnum.Core/FastEnum.cs +++ b/src/libs/FastEnum.Core/FastEnum.cs @@ -143,7 +143,7 @@ public static bool IsDefined(T value) [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsDefined(ReadOnlySpan name) where T : struct, Enum - => EnumInfo.s_memberByNameCaseSensitive.ContainsKey(name); + => EnumInfo.MemberByNameCaseSensitive.s_value.ContainsKey(name); /// @@ -251,7 +251,7 @@ public static bool TryParse(ReadOnlySpan value, bool ignoreCase, out T [MethodImpl(MethodImplOptions.AggressiveInlining)] static bool tryParseNameCaseSensitive(ReadOnlySpan name, out T result) { - if (EnumInfo.s_memberByNameCaseSensitive.TryGetValue(name, out var member)) + if (EnumInfo.MemberByNameCaseSensitive.s_value.TryGetValue(name, out var member)) { result = member.Value; return true; @@ -264,7 +264,7 @@ static bool tryParseNameCaseSensitive(ReadOnlySpan name, out T result) [MethodImpl(MethodImplOptions.AggressiveInlining)] static bool tryParseNameCaseInsensitive(ReadOnlySpan name, out T result) { - if (EnumInfo.s_memberByNameCaseInsensitive.TryGetValue(name, out var member)) + if (EnumInfo.MemberByNameCaseInsensitive.s_value.TryGetValue(name, out var member)) { result = member.Value; return true; diff --git a/src/libs/FastEnum.Core/FastEnumExtensions.cs b/src/libs/FastEnum.Core/FastEnumExtensions.cs index 2d7b4f29..f6c6457d 100644 --- a/src/libs/FastEnum.Core/FastEnumExtensions.cs +++ b/src/libs/FastEnum.Core/FastEnumExtensions.cs @@ -237,7 +237,8 @@ public bool IsDefined() { ArgumentNullException.ThrowIfNull(@this); - if (@this.Labels.TryGetValue(index, out var label)) + var label = @this.GetLabelOrUndefined(index); + if (!ReferenceEquals(label, JitOptimization.MemberHelper.s_undefinedLabel)) return label; if (throwIfNotFound) diff --git a/src/libs/FastEnum.Core/Internals/CaseStringDictionary.cs b/src/libs/FastEnum.Core/Internals/CaseStringDictionary.cs index 74c714b1..08b18862 100644 --- a/src/libs/FastEnum.Core/Internals/CaseStringDictionary.cs +++ b/src/libs/FastEnum.Core/Internals/CaseStringDictionary.cs @@ -1,4 +1,5 @@ using System; +using System.Buffers; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Text; @@ -13,16 +14,18 @@ internal sealed class CaseSensitiveStringDictionary #region Fields private readonly Entry[] _buckets; private readonly int _size; - private readonly uint _indexFor; // uint, so that the 32-bit masked hash is zero-extended to the offset for free + private readonly uint _multiplier; + private readonly int _shift; #endregion #region Constructors - private CaseSensitiveStringDictionary(Entry[] buckets, int size, uint indexFor) + private CaseSensitiveStringDictionary(Entry[] buckets, int size, uint multiplier, int shift) { this._buckets = buckets; this._size = size; - this._indexFor = indexFor; + this._multiplier = multiplier; + this._shift = shift; } #endregion @@ -30,27 +33,49 @@ private CaseSensitiveStringDictionary(Entry[] buckets, int size, uint indexFor) #region Factories public static CaseSensitiveStringDictionary Create(ReadOnlySpan values) { - var capacity = JitOptimization.CaseStringDictionary.CalculateCapacity(values.Length); - var buckets = new Entry[capacity]; - var indexFor = (uint)(buckets.Length - 1); - var size = 0; - foreach (var x in values) + int[]? rented = null; + var hashes + = (values.Length <= JitOptimization.CaseStringDictionary.MaxStackBufferLength) + ? stackalloc int[JitOptimization.CaseStringDictionary.MaxStackBufferLength] + : (rented = ArrayPool.Shared.Rent(values.Length)); + try { - var key = x.Name; - var value = x; - if (!tryAdd(buckets, key, value, indexFor)) - ThrowHelper.ThrowDuplicatedKeyExists(key); - size++; + return build(values, hashes[..values.Length]); + } + finally + { + if (rented is not null) + ArrayPool.Shared.Return(rented); } - - return new(buckets, size, indexFor); #region Local Functions - static bool tryAdd(Entry[] buckets, string key, TValue value, uint indexFor) + [MethodImpl(MethodImplOptions.NoInlining)] // has the loops; see JitOptimization.CaseStringDictionary.MaxStackBufferLength + static CaseSensitiveStringDictionary build(ReadOnlySpan values, Span hashes) + { + var capacity = JitOptimization.CaseStringDictionary.CalculateCapacity(values.Length); + var buckets = new Entry[capacity]; + var shift = JitOptimization.CaseStringDictionary.CalculateShift(capacity); + for (var i = 0; i < values.Length; i++) + hashes[i] = StringHelper.CaseSensitive.GetHashCode(values[i].Name); + + var multiplier = JitOptimization.CaseStringDictionary.ChooseMultiplier(hashes, capacity, shift); + var size = 0; + for (var i = 0; i < values.Length; i++) + { + var key = values[i].Name; + var value = values[i]; + if (!tryAdd(buckets, key, value, hashes[i], multiplier, shift)) + ThrowHelper.ThrowDuplicatedKeyExists(key); + size++; + } + return new(buckets, size, multiplier, shift); + } + + + static bool tryAdd(Entry[] buckets, string key, TValue value, int hash, uint multiplier, int shift) { - var hash = StringHelper.CaseSensitive.GetHashCode(key); - var index = (nuint)((uint)hash & indexFor); + var index = JitOptimization.CaseStringDictionary.ToIndex(hash, multiplier, shift); var target = buckets.At(index); if (target is null) { @@ -94,7 +119,7 @@ public bool ContainsKey(ReadOnlySpan key) public bool TryGetValue(ReadOnlySpan key, [MaybeNullWhen(false)] out TValue value) { var hash = StringHelper.CaseSensitive.GetHashCode(key); - var index = (nuint)((uint)hash & this._indexFor); // mask in 32-bit, then zero-extend (free right after a 32-bit op, unlike sign extension) + var index = JitOptimization.CaseStringDictionary.ToIndex(hash, this._multiplier, this._shift); var entry = this._buckets.At(index); while (entry is not null) { @@ -129,16 +154,18 @@ internal sealed class CaseInsensitiveStringDictionary #region Fields private readonly Entry[] _buckets; private readonly int _size; - private readonly uint _indexFor; // uint, so that the 32-bit masked hash is zero-extended to the offset for free + private readonly uint _multiplier; + private readonly int _shift; #endregion #region Constructors - private CaseInsensitiveStringDictionary(Entry[] buckets, int size, uint indexFor) + private CaseInsensitiveStringDictionary(Entry[] buckets, int size, uint multiplier, int shift) { this._buckets = buckets; this._size = size; - this._indexFor = indexFor; + this._multiplier = multiplier; + this._shift = shift; } #endregion @@ -146,26 +173,50 @@ private CaseInsensitiveStringDictionary(Entry[] buckets, int size, uint indexFor #region Factories public static CaseInsensitiveStringDictionary Create(ReadOnlySpan values) { - var capacity = JitOptimization.CaseStringDictionary.CalculateCapacity(values.Length); - var buckets = new Entry[capacity]; - var indexFor = (uint)(buckets.Length - 1); - var size = 0; - foreach (var x in values) + // note: + // - Names that differ only in case are skipped, but they are counted when choosing the multiplier. + // They share the same hash, so they only make the measured chains a bit longer than the real ones. + + int[]? rented = null; + var hashes + = (values.Length <= JitOptimization.CaseStringDictionary.MaxStackBufferLength) + ? stackalloc int[JitOptimization.CaseStringDictionary.MaxStackBufferLength] + : (rented = ArrayPool.Shared.Rent(values.Length)); + try { - var key = x.Name; - var value = x; - if (tryAdd(buckets, key, value, indexFor)) - size++; + return build(values, hashes[..values.Length]); + } + finally + { + if (rented is not null) + ArrayPool.Shared.Return(rented); } - - return new(buckets, size, indexFor); #region Local Functions - static bool tryAdd(Entry[] buckets, string key, TValue value, uint indexFor) + [MethodImpl(MethodImplOptions.NoInlining)] // has the loops; see JitOptimization.CaseStringDictionary.MaxStackBufferLength + static CaseInsensitiveStringDictionary build(ReadOnlySpan values, Span hashes) + { + var capacity = JitOptimization.CaseStringDictionary.CalculateCapacity(values.Length); + var buckets = new Entry[capacity]; + var shift = JitOptimization.CaseStringDictionary.CalculateShift(capacity); + for (var i = 0; i < values.Length; i++) + hashes[i] = StringHelper.CaseInsensitive.GetHashCode(values[i].Name); + + var multiplier = JitOptimization.CaseStringDictionary.ChooseMultiplier(hashes, capacity, shift); + var size = 0; + for (var i = 0; i < values.Length; i++) + { + if (tryAdd(buckets, values[i].Name, values[i], hashes[i], multiplier, shift)) + size++; + } + return new(buckets, size, multiplier, shift); + } + + + static bool tryAdd(Entry[] buckets, string key, TValue value, int hash, uint multiplier, int shift) { - var hash = StringHelper.CaseInsensitive.GetHashCode(key); - var index = (nuint)((uint)hash & indexFor); + var index = JitOptimization.CaseStringDictionary.ToIndex(hash, multiplier, shift); var target = buckets.At(index); if (target is null) { @@ -209,7 +260,7 @@ public bool ContainsKey(ReadOnlySpan key) public bool TryGetValue(ReadOnlySpan key, [MaybeNullWhen(false)] out TValue value) { var hash = StringHelper.CaseInsensitive.GetHashCode(key); - var index = (nuint)((uint)hash & this._indexFor); // mask in 32-bit, then zero-extend (free right after a 32-bit op, unlike sign extension) + var index = JitOptimization.CaseStringDictionary.ToIndex(hash, this._multiplier, this._shift); var entry = this._buckets.At(index); while (entry is not null) { diff --git a/src/libs/FastEnum.Core/Internals/EnumInfo.cs b/src/libs/FastEnum.Core/Internals/EnumInfo.cs index 4ef0b869..bbfa665e 100644 --- a/src/libs/FastEnum.Core/Internals/EnumInfo.cs +++ b/src/libs/FastEnum.Core/Internals/EnumInfo.cs @@ -16,8 +16,6 @@ internal static class EnumInfo public static readonly T[] s_values; public static readonly Member[] s_members; public static readonly Member[] s_orderedMembers; - public static readonly CaseSensitiveStringDictionary> s_memberByNameCaseSensitive; - public static readonly CaseInsensitiveStringDictionary> s_memberByNameCaseInsensitive; public static readonly EnumKeyDictionary> s_memberByValue; public static readonly T s_minValue; public static readonly T s_maxValue; @@ -31,13 +29,11 @@ internal static class EnumInfo static EnumInfo() { s_type = typeof(T); - s_typeCode = Type.GetTypeCode(s_type); + s_typeCode = UnderlyingOperation.TypeCodeOf.s_value; // initializes it as well; see the note there s_names = Enum.GetNames(s_type); s_values = Enum.GetValues(); s_members = toMembers(s_names, s_values); s_orderedMembers = JitOptimization.EnumInfo.ToOrderedMembers(s_members, MemoryMarshal.AsBytes(s_values), s_typeCode, out s_isContinuous); - s_memberByNameCaseSensitive = CaseSensitiveStringDictionary>.Create(s_members); - s_memberByNameCaseInsensitive = CaseInsensitiveStringDictionary>.Create(s_members); if (!s_isContinuous) { // note: @@ -78,4 +74,33 @@ static Member[] toMembers(ReadOnlySpan names, ReadOnlySpan values) #endregion } #endregion + + + #region Nested Types + // note: + // - The lookup tables by name are used only by IsDefined(name) / Parse() / TryParse(), and the case-insensitive one only with ignoreCase. + // They are built at their first use, so an application that only formats values (GetName / ToString / IsDefined(value)) never pays for them. + // - Each lives in its own nested class, because the static constructor of a class is the cheapest lazy initialization: + // Tier1 code compiled after the initialization reads the field as a constant without any check, the same as the fields of EnumInfo. + // - The static constructors are explicit, so the classes are not beforefieldinit. + // JIT may run the static constructor of a beforefieldinit class while compiling a method that refers to it, + // so TryParse() would build both tables even if ignoreCase is never true. + + public static class MemberByNameCaseSensitive + { + public static readonly CaseSensitiveStringDictionary> s_value; + + static MemberByNameCaseSensitive() + => s_value = CaseSensitiveStringDictionary>.Create(s_members); + } + + + public static class MemberByNameCaseInsensitive + { + public static readonly CaseInsensitiveStringDictionary> s_value; + + static MemberByNameCaseInsensitive() + => s_value = CaseInsensitiveStringDictionary>.Create(s_members); + } + #endregion } diff --git a/src/libs/FastEnum.Core/Internals/JitOptimization.cs b/src/libs/FastEnum.Core/Internals/JitOptimization.cs index d1d495cc..ec00c676 100644 --- a/src/libs/FastEnum.Core/Internals/JitOptimization.cs +++ b/src/libs/FastEnum.Core/Internals/JitOptimization.cs @@ -1,6 +1,5 @@ using System; using System.Buffers; -using System.Collections.Frozen; using System.Numerics; using System.Reflection; using System.Runtime.CompilerServices; @@ -34,6 +33,120 @@ public static int CalculateCapacity(int collectionSize) const int initialSize = 4; return Math.Max(size, initialSize); } + + + public static int CalculateShift(int capacity) + { + // note: + // - The capacity is the power of 2 and at least 4, so the shift is 30 or less and never 32 (C# masks the shift count by 31). + return 32 - BitOperations.Log2((uint)capacity); + } + + + /// + /// The working buffers of up to this length are taken from the stack instead of ArrayPool (2 KB of int). + /// + /// + /// Two buffers are in use at once (the hashes and the counts). The second buffer of the same size returned to ArrayPool<int>.Shared + /// does not fit the thread-local slot and makes the pool create its per-core stacks for the size, which it keeps for the process: + /// +25 KB retained at the first use of 21 BCL enums, more than the tables themselves cost. + /// + /// A method with stackalloc must not have loops: OSR does not support stackalloc, so such a method skips Tier0 and is compiled + /// with full optimization at its first call (+2.4 ms of JIT at the first use of 20 BCL enums). The buffer is taken in a method + /// without loops and passed to a NoInlining method that has them. + /// + /// + public const int MaxStackBufferLength = 512; + + + public static uint ChooseMultiplier(ReadOnlySpan hashes, int capacity, int shift) + { + // note: + // - The hash of StringHelper puts the last character in the low bits and the length in the high bits. + // Masking its low bits uses only the last character for a small table (e.g. all names of DayOfWeek end with 'y' and share one bucket). + // - Multiply-shift takes the high bits of the product, which depend on every bit of the hash. + // However, no single multiplier is the best for every set of names, and the keys are fixed on creation, so the best one is searched. + // - The first candidate is 2^shift; (hash * 2^shift) >> shift is the same as masking the low bits, so the total of positions is never larger than with masking. + // - The cost of a lookup that finds the key is the position in the chain, so the total of positions comes first and the longest chain is the tiebreaker. + // The longest chain can still be longer than with masking, so a miss that falls into it may compare more keys. + // - The search ends as soon as all keys get their own bucket. + + int[]? rented = null; + var counts + = (capacity <= MaxStackBufferLength) + ? stackalloc int[MaxStackBufferLength] + : (rented = ArrayPool.Shared.Rent(capacity)); + try + { + return search(hashes, counts[..capacity], shift); + } + finally + { + if (rented is not null) + ArrayPool.Shared.Return(rented); + } + + + #region Local Functions + [MethodImpl(MethodImplOptions.NoInlining)] // has the loops; see MaxStackBufferLength + static uint search(ReadOnlySpan hashes, Span counts, int shift) + { + const int maxCandidates = 64; + var best = 1u << shift; + var (bestTotal, bestMax) = measure(hashes, best, shift, counts); + var candidate = 0x9E3779B9u; // 2^32 / golden ratio + for (var i = 0; i < maxCandidates && bestTotal > hashes.Length; i++) + { + var (total, max) = measure(hashes, candidate, shift, counts); + if (total < bestTotal || (total == bestTotal && max < bestMax)) + { + best = candidate; + bestTotal = total; + bestMax = max; + } + candidate = nextCandidate(candidate); + } + return best; + } + + + static (int total, int max) measure(ReadOnlySpan hashes, uint multiplier, int shift, Span counts) + { + counts.Clear(); + var total = 0; + var max = 0; + foreach (var x in hashes) + { + var count = ++counts[(int)ToIndex(x, multiplier, shift)]; + total += count; + max = Math.Max(max, count); + } + return (total, max); + } + + + static uint nextCandidate(uint x) + { + // note: + // - xorshift32. It is deterministic, so the same names always get the same table. + // - Multiplier must be odd. + + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + return x | 1; + } + #endregion + } + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static nuint ToIndex(int hash, uint multiplier, int shift) + { + // note: + // - Computed in 32 bits, so the result is zero-extended to the offset for free. + return (nuint)(((uint)hash * multiplier) >> shift); + } #endregion } @@ -490,10 +603,93 @@ public static class MemberHelper #region Methods - public static FrozenDictionary CreateLabels(FieldInfo field) - => field - .GetCustomAttributes() - .ToFrozenDictionary(static x => x.Index, static x => x.Value); + public static object CreateLabels(FieldInfo field) + { + // note: + // - FrozenDictionary allocated an intermediate Dictionary<,>, its own arrays and an object on creation for each member. + // - Labels are usually indexed from 0 densely, so they are held in an array indexed by the label index (= string?[]); a lookup is a range check and a load. + // The slot of an undefined index holds s_undefinedLabel, because null is a valid label. + // - A negative or large index would make the array sparse, so such labels are held as pairs and searched linearly (= Label[]). + // - The same index twice throws ArgumentException, the same as ToFrozenDictionary() did. + // - No label shares one empty array. + + var attributes = Attribute.GetCustomAttributes(field, typeof(LabelAttribute), inherit: false); + if (attributes.Length is 0) + return s_noLabels; + + var labels = new Label[attributes.Length]; + var maxIndex = 0; + var isDense = true; + for (var i = 0; i < attributes.Length; i++) + { + var attr = (LabelAttribute)attributes[i]; + for (var j = 0; j < i; j++) + { + if (labels[j].Index == attr.Index) + throw new ArgumentException($"An item with the same key has already been added. Key: {attr.Index}"); + } + labels[i] = new(attr.Index, attr.Value); + maxIndex = Math.Max(maxIndex, attr.Index); + isDense &= attr.Index >= 0; + } + + const int maxDenseLength = 16; + if (!isDense || maxIndex >= Math.Max(maxDenseLength, attributes.Length * 2)) + return labels; + + var dense = new string?[maxIndex + 1]; + dense.AsSpan().Fill(s_undefinedLabel); + foreach (var x in labels) + dense[x.Index] = x.Value; + return dense; + } + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static string? GetLabelOrUndefined(object labels, int index) + { + // note: + // - Returns s_undefinedLabel instead of `bool TryGetLabel(..., out string? label)`. + // The out parameter takes the address of the local, so JIT keeps it on the stack and the inlined lookup stores / loads / clears it every time. + + if (labels is string?[] dense) + return ((uint)index < (uint)dense.Length) ? dense[index] : s_undefinedLabel; + + return getSparse(Unsafe.As(labels), index); + + + #region Local Functions + static string? getSparse(Label[] labels, int index) + { + foreach (var x in labels) + { + if (x.Index == index) + return x.Value; + } + return s_undefinedLabel; + } + #endregion + } + #endregion + + + #region Fields + private static readonly string?[] s_noLabels = []; + + /// + /// Marks that the label of the index is not defined. It is distinguished by reference, because is a valid label. + /// + /// A new instance, so it is never the same reference as an interned string literal. + public static readonly string s_undefinedLabel = new('\0', 1); + #endregion + + + #region Nested Types + public readonly struct Label(int index, string? value) + { + public readonly int Index = index; + public readonly string? Value = value; + } #endregion } } diff --git a/src/libs/FastEnum.Core/Internals/StringHelper.cs b/src/libs/FastEnum.Core/Internals/StringHelper.cs index 2ba7db7c..bd272d12 100644 --- a/src/libs/FastEnum.Core/Internals/StringHelper.cs +++ b/src/libs/FastEnum.Core/Internals/StringHelper.cs @@ -178,7 +178,10 @@ public static bool EqualsAscii(ReadOnlySpan ascii, ReadOnlySpan othe // // Why this is faster: // - `MemoryExtensions.Equals()` isn't inlined and branches on StringComparison every time. - // - Enum names are short, so two overlapping loads cover the whole string without a loop. (4-8 chars: 64 bits x 2 / 8-16 chars: 128 bits x 2) + // - Enum names are short, so overlapping loads cover the whole string without a loop. + // (4-8 chars: 64 bits x 2 / 8-16 chars: 128 bits x 2 / 17-32 chars: 256 bits x 2 or 128 bits x 4) + // - About a fifth of the names of BCL enums are longer than 16 chars. OrdinalIgnoreCase takes 2.6-2.8 ns for 17-32 chars, and this takes 1.6-1.7 ns. + // - Shorter than 4 chars is left to OrdinalIgnoreCase; it was measured as fast as, or faster than, two overlapping 32-bit loads. var length = ascii.Length; if (length != other.Length) @@ -188,12 +191,36 @@ public static bool EqualsAscii(ReadOnlySpan ascii, ReadOnlySpan othe ref var y = ref Unsafe.As(ref MemoryMarshal.GetReference(other)); if (length >= 8) { - if (length <= 16 && Vector128.IsHardwareAccelerated) + if (length <= 16) { - var tail = (nuint)(uint)(length - 8) * sizeof(char); - var head = diff128(Vector128.LoadUnsafe(ref x).AsUInt16(), Vector128.LoadUnsafe(ref y).AsUInt16()); - var rest = diff128(Vector128.LoadUnsafe(ref x, tail).AsUInt16(), Vector128.LoadUnsafe(ref y, tail).AsUInt16()); - return (head | rest) == Vector128.Zero; + if (Vector128.IsHardwareAccelerated) + { + var tail = (nuint)(uint)(length - 8) * sizeof(char); + var head = diff128(Vector128.LoadUnsafe(ref x).AsUInt16(), Vector128.LoadUnsafe(ref y).AsUInt16()); + var rest = diff128(Vector128.LoadUnsafe(ref x, tail).AsUInt16(), Vector128.LoadUnsafe(ref y, tail).AsUInt16()); + return (head | rest) == Vector128.Zero; + } + } + else if (length <= 32) + { + if (Vector256.IsHardwareAccelerated) + { + var tail = (nuint)(uint)(length - 16) * sizeof(char); + var head = diff256(Vector256.LoadUnsafe(ref x).AsUInt16(), Vector256.LoadUnsafe(ref y).AsUInt16()); + var rest = diff256(Vector256.LoadUnsafe(ref x, tail).AsUInt16(), Vector256.LoadUnsafe(ref y, tail).AsUInt16()); + return (head | rest) == Vector256.Zero; + } + if (Vector128.IsHardwareAccelerated) + { + const nuint second = 8 * sizeof(char); + var third = (nuint)(uint)(length - 16) * sizeof(char); + var fourth = (nuint)(uint)(length - 8) * sizeof(char); + var a = diff128(Vector128.LoadUnsafe(ref x).AsUInt16(), Vector128.LoadUnsafe(ref y).AsUInt16()); + var b = diff128(Vector128.LoadUnsafe(ref x, second).AsUInt16(), Vector128.LoadUnsafe(ref y, second).AsUInt16()); + var c = diff128(Vector128.LoadUnsafe(ref x, third).AsUInt16(), Vector128.LoadUnsafe(ref y, third).AsUInt16()); + var d = diff128(Vector128.LoadUnsafe(ref x, fourth).AsUInt16(), Vector128.LoadUnsafe(ref y, fourth).AsUInt16()); + return (a | b | c | d) == Vector128.Zero; + } } } else if (length >= 4) @@ -234,6 +261,19 @@ static Vector128 diff128(Vector128 ascii, Vector128 othe var caseBit = letter & caseMask; return (ascii ^ other) & ~caseBit; } + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + static Vector256 diff256(Vector256 ascii, Vector256 other) + { + var caseMask = Vector256.Create((ushort)0x20); + var lower = ascii | caseMask; + var offset = lower - Vector256.Create((ushort)'a'); // distance from 'a' (wraps around if below 'a') + var alphabetCount = Vector256.Create((ushort)26); + var letter = Vector256.LessThan(offset, alphabetCount); // all bits set if 'a' <= lower <= 'z' + var caseBit = letter & caseMask; + return (ascii ^ other) & ~caseBit; + } #endregion } } diff --git a/src/libs/FastEnum.Core/Internals/UnderlyingOperation.cs b/src/libs/FastEnum.Core/Internals/UnderlyingOperation.cs index 24f0b59d..515f81f6 100644 --- a/src/libs/FastEnum.Core/Internals/UnderlyingOperation.cs +++ b/src/libs/FastEnum.Core/Internals/UnderlyingOperation.cs @@ -71,7 +71,7 @@ public static bool IsDefined(T value) public static string ToNumberString(T value) where T : struct, Enum { - switch (EnumInfo.s_typeCode) + switch (TypeCodeOf.s_value) { case TypeCode.SByte: return SByteOperation.ToNumberString(value); @@ -100,7 +100,7 @@ public static string ToNumberString(T value) public static bool TryParseValue(ReadOnlySpan text, out T result) where T : struct, Enum { - switch (EnumInfo.s_typeCode) + switch (TypeCodeOf.s_value) { case TypeCode.SByte: return SByteOperation.TryParseValue(text, out result); @@ -155,6 +155,35 @@ public static bool TryGetMember(T value, [NotNullWhen(true)] out Member? r #region Nested Types + /// + /// Holds only the type code of the enum, apart from . + /// + public static class TypeCodeOf + where T : struct, Enum + { + // note: + // - ToNumberString() / TryParseValue() need nothing but the type code. They are also used through IFastEnumBooster, + // whose purpose is to avoid the reflection and the tables that the static constructor of EnumInfo builds. + // - Reading EnumInfo.s_typeCode would run that static constructor just to get the type code. + // - This is a static readonly field too, so JIT folds the switch on it into one branch, but only if this class is already initialized when the caller is compiled. + // EnumInfo reads it in its static constructor, so it is always initialized before the members are looked up. + // Otherwise, e.g. ToString() of a defined value never runs ToNumberString(), and the whole switch stays in the code (+1.2 KB, +8% in ToString_Discontinuous). + // - An enum of char or bool (possible in IL, not in C#) fails here, as it fails in the static constructor of EnumInfo, + // so that parsing a number does not return false silently. + public static readonly TypeCode s_value = GetSupportedTypeCode(typeof(T)); + } + + + /// Not generic, so that JIT compiles it only once for all enum types. + private static TypeCode GetSupportedTypeCode(Type type) + { + var code = Type.GetTypeCode(type); + if (code is < TypeCode.SByte or > TypeCode.UInt64) + throw new InvalidOperationException($"The underlying type of {type} is not supported."); + return code; + } + + /// /// Provides the operations for the specified underlying type. /// diff --git a/src/libs/FastEnum.Core/Member.cs b/src/libs/FastEnum.Core/Member.cs index a6a15fc5..fd5e82b1 100644 --- a/src/libs/FastEnum.Core/Member.cs +++ b/src/libs/FastEnum.Core/Member.cs @@ -1,7 +1,7 @@ using System; -using System.Collections.Frozen; using System.Collections.Immutable; using System.Reflection; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Text; @@ -97,14 +97,15 @@ public EnumMemberAttribute? EnumMemberAttribute /// /// Gets the labels of specified enumration member. /// - internal FrozenDictionary Labels + /// indexed by the label index, or [] for sparse indexes. + internal object Labels { get { // note: // - It is used only by GetLabel(), so it is created at the first access instead of the constructor. // - The result is never null (it is empty when no LabelAttribute is defined), so null means "not created yet". - // - Interlocked.CompareExchange() publishes only one dictionary even if multiple threads create it at the same time. + // - Interlocked.CompareExchange() publishes only one array even if multiple threads create it at the same time. var labels = this._labels; if (labels is null) @@ -115,7 +116,19 @@ public EnumMemberAttribute? EnumMemberAttribute return labels; } } - private FrozenDictionary? _labels; + private object? _labels; + #endregion + + + #region Methods + /// + /// Gets the label of the specified index. + /// + /// + /// The label, or if it is not defined. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal string? GetLabelOrUndefined(int index) + => JitOptimization.MemberHelper.GetLabelOrUndefined(this.Labels, index); #endregion diff --git a/src/libs/FastEnum.Generators/FastEnumBoosterGenerator.cs b/src/libs/FastEnum.Generators/FastEnumBoosterGenerator.cs index f67403f2..af40d3e5 100644 --- a/src/libs/FastEnum.Generators/FastEnumBoosterGenerator.cs +++ b/src/libs/FastEnum.Generators/FastEnumBoosterGenerator.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; +using System.Threading; using FastEnumUtility.Generators.Internals; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; @@ -35,35 +36,35 @@ or StructDeclarationSyntax }, transform: static (context, cancellationToken) => { + // note: + // - The pipeline compares the value with the previous run, and skips the output step if it is equal. + // - GeneratorAttributeSyntaxContext holds the semantic model, which is new for every compilation (= every keystroke in IDE). + // Passing it as is made every booster look changed, so all of them were generated and parsed again on every edit. + // - Only the strings needed for the output are extracted here, into records compared by value. + // Symbols and syntax nodes are not kept either, so the old compilations are not held by the pipeline. + cancellationToken.ThrowIfCancellationRequested(); - return context; + return BoosterModel.Create(new GenerateParameters(context), cancellationToken); } ); - var parseOptions = context.ParseOptionsProvider; - var source = typeDeclarations.Combine(parseOptions); - context.RegisterSourceOutput(source, static (context, source) => + context.RegisterSourceOutput(typeDeclarations, static (context, model) => { - var syntax = source.Left; - var options = (CSharpParseOptions)source.Right; - var param = new GenerateParameters(syntax, options); - - var diagnostic = Diagnose(param); - if (diagnostic is not null) + if (model.Diagnostic is not null) { - context.ReportDiagnostic(diagnostic); + context.ReportDiagnostic(model.Diagnostic.ToDiagnostic()); return; } - var code = Generate(param); - context.AddSource(param.FileName, code); + var code = Generate(model); + context.AddSource(model.FileName, code); }); } #endregion #region Helpers - private static Diagnostic? Diagnose(GenerateParameters param) + private static DiagnosticModel? Diagnose(GenerateParameters param) { var containerType = param.ContainerType; var enumType = param.EnumType; @@ -74,7 +75,7 @@ or StructDeclarationSyntax var descriptor = DiagnosticDescriptorProvider.MustBePartial; var location = containerType.SyntaxNode.Identifier.GetLocation(); var args = containerType.TypeName; - return Diagnostic.Create(descriptor, location, args); + return DiagnosticModel.Create(descriptor, location, args); } //--- Disallow nested type @@ -83,7 +84,7 @@ or StructDeclarationSyntax var descriptor = DiagnosticDescriptorProvider.MustNotBeNested; var location = containerType.SyntaxNode.Identifier.GetLocation(); var args = containerType.TypeName; - return Diagnostic.Create(descriptor, location, args); + return DiagnosticModel.Create(descriptor, location, args); } //--- Allow public or internal only @@ -91,8 +92,8 @@ or StructDeclarationSyntax { var descriptor = DiagnosticDescriptorProvider.MustBePublicOrInternal; var location = enumType.SyntaxNode.GetLocation(); - var args = enumType.SyntaxNode.GetText(); - return Diagnostic.Create(descriptor, location, args); + var args = enumType.SyntaxNode.GetText().ToString(); + return DiagnosticModel.Create(descriptor, location, args); } //--- Generic type argument must be enum type @@ -100,15 +101,15 @@ or StructDeclarationSyntax { var descriptor = DiagnosticDescriptorProvider.MustBeEnumType; var location = enumType.SyntaxNode.GetLocation(); - var args = enumType.SyntaxNode.GetText(); - return Diagnostic.Create(descriptor, location, args); + var args = enumType.SyntaxNode.GetText().ToString(); + return DiagnosticModel.Create(descriptor, location, args); } return null; } - private static string Generate(GenerateParameters param) + private static string Generate(BoosterModel param) { var sb = new StringBuilder(); emitHeader(sb); @@ -135,7 +136,7 @@ static void emitHeader(StringBuilder sb) } - static void emitPragmaWarningDisable(StringBuilder sb, GenerateParameters param) + static void emitPragmaWarningDisable(StringBuilder sb, BoosterModel param) { sb.AppendLine(""" @@ -144,28 +145,7 @@ static void emitPragmaWarningDisable(StringBuilder sb, GenerateParameters param) """); //--- supports [Obsolete(DiagnosticId = "xxx")] - IEnumerable types = [param.EnumType.TypeSymbol]; - IEnumerable fields = param.EnumType.Fields; - var diagnosticIds - = types - .Concat(fields) - .SelectMany(static x => x.GetAttributes()) - .Where(static x => - { - var @class = x.AttributeClass; - return (@class?.ContainingNamespace.MetadataName == typeof(ObsoleteAttribute).Namespace) - && (@class?.MetadataName is nameof(ObsoleteAttribute)); - }) - .SelectMany(static x => x.NamedArguments) - .Where(static x => x.Key is "DiagnosticId") - .Select(static x => x.Value) - .Where(static x => x.Type?.SpecialType is SpecialType.System_String) - .Select(static x => (string?)x.Value) - .Select(static x => x?.Trim()) - .Where(static x => !string.IsNullOrWhiteSpace(x)) - .Distinct() - .OrderBy(static x => x); - foreach (var x in diagnosticIds) + foreach (var x in param.EnumType.ObsoleteDiagnosticIds) sb.AppendLine($"#pragma warning disable {x}"); } @@ -182,7 +162,7 @@ static void emitUsingDirectives(StringBuilder sb) } - static void emitNamespace(StringBuilder sb, GenerateParameters param) + static void emitNamespace(StringBuilder sb, BoosterModel param) { var container = param.ContainerType; if (container.IsGlobalNamespace) @@ -195,7 +175,7 @@ namespace {container.Namespace}; } - static void emitBooster_Start(StringBuilder sb, GenerateParameters param) + static void emitBooster_Start(StringBuilder sb, BoosterModel param) { var container = param.ContainerType; var @enum = param.EnumType; @@ -208,7 +188,7 @@ static void emitBooster_Start(StringBuilder sb, GenerateParameters param) } - static void emitGetName(StringBuilder sb, GenerateParameters param) + static void emitGetName(StringBuilder sb, BoosterModel param) { var @enum = param.EnumType; sb.AppendLine($$""" @@ -231,7 +211,7 @@ static void emitGetName(StringBuilder sb, GenerateParameters param) } - static void emitIsDefined_Enum(StringBuilder sb, GenerateParameters param) + static void emitIsDefined_Enum(StringBuilder sb, BoosterModel param) { var @enum = param.EnumType; sb.AppendLine($$""" @@ -255,7 +235,7 @@ static void emitIsDefined_Enum(StringBuilder sb, GenerateParameters param) } - static void emitIsDefined_String(StringBuilder sb, GenerateParameters param) + static void emitIsDefined_String(StringBuilder sb, BoosterModel param) { var @enum = param.EnumType; sb.AppendLine($$""" @@ -279,7 +259,7 @@ static void emitIsDefined_String(StringBuilder sb, GenerateParameters param) } - static void emitTryParseName(StringBuilder sb, GenerateParameters param) + static void emitTryParseName(StringBuilder sb, BoosterModel param) { var @enum = param.EnumType; sb.AppendLine($$""" @@ -370,10 +350,101 @@ static void emitBooster_End(StringBuilder sb) #region Nested Types + /// + /// Everything the output step needs, compared by value. + /// + private sealed record BoosterModel(string FileName, DiagnosticModel? Diagnostic, ContainerModel ContainerType, EnumModel EnumType) + { + public static BoosterModel Create(GenerateParameters param, CancellationToken cancellationToken) + { + var container = param.ContainerType; + var containerModel = new ContainerModel(container.IsGlobalNamespace, container.Namespace, container.TypeKind, container.TypeName); + var diagnostic = Diagnose(param); + if (diagnostic is not null) + return new(param.FileName, diagnostic, containerModel, new(param.EnumType.TypeName, new([]), new([]), new([]))); + + cancellationToken.ThrowIfCancellationRequested(); + var @enum = param.EnumType; + var enumModel = new EnumModel( + @enum.TypeName, + new(@enum.Fields.Select(static x => new FieldModel(x.Name)).ToArray()), + new(@enum.DistinctedFields.Select(static x => new FieldModel(x.Name)).ToArray()), + new(getObsoleteDiagnosticIds(@enum))); + return new(param.FileName, null, containerModel, enumModel); + + + #region Local Functions + static string[] getObsoleteDiagnosticIds(EnumTypeMetadata @enum) + { + //--- supports [Obsolete(DiagnosticId = "xxx")] + IEnumerable types = [@enum.TypeSymbol]; + IEnumerable fields = @enum.Fields; + return types + .Concat(fields) + .SelectMany(static x => x.GetAttributes()) + .Where(static x => + { + var @class = x.AttributeClass; + return (@class?.ContainingNamespace.MetadataName == typeof(ObsoleteAttribute).Namespace) + && (@class?.MetadataName is nameof(ObsoleteAttribute)); + }) + .SelectMany(static x => x.NamedArguments) + .Where(static x => x.Key is "DiagnosticId") + .Select(static x => x.Value) + .Where(static x => x.Type?.SpecialType is SpecialType.System_String) + .Select(static x => (string?)x.Value) + .Select(static x => x?.Trim()) + .Where(static x => !string.IsNullOrWhiteSpace(x)) + .Distinct() + .OrderBy(static x => x) + .ToArray()!; + } + #endregion + } + } + + + private sealed record ContainerModel(bool IsGlobalNamespace, string Namespace, string TypeKind, string TypeName); + + + private sealed record EnumModel(string TypeName, EquatableArray Fields, EquatableArray DistinctedFields, EquatableArray ObsoleteDiagnosticIds); + + + private sealed record FieldModel(string Name); + + + /// + /// A diagnostic, compared by value. + /// + /// + /// The is kept as is. A location in source equals another one with the same syntax tree and span, + /// and the syntax tree of a file stays the same object until the file is edited, so the model still equals the previous one. + /// A location created again from the file path would not be in source, and the compiler would ignore + /// #pragma warning disable and .editorconfig for the diagnostic. + /// + private sealed record DiagnosticModel(string Id, Location Location, string Argument) + { + public static DiagnosticModel Create(DiagnosticDescriptor descriptor, Location location, string argument) + => new(descriptor.Id, location, argument); + + + public Diagnostic ToDiagnostic() + { + var descriptor = this.Id switch + { + "FE0001" => DiagnosticDescriptorProvider.MustBePartial, + "FE0002" => DiagnosticDescriptorProvider.MustNotBeNested, + "FE0003" => DiagnosticDescriptorProvider.MustBePublicOrInternal, + _ => DiagnosticDescriptorProvider.MustBeEnumType, + }; + return Diagnostic.Create(descriptor, this.Location, this.Argument); + } + } + + private sealed class GenerateParameters { #region Properties - public LanguageVersion LanguageVersion { get; } public string FileName { get; } public ContainerTypeMetadata ContainerType { get; } public EnumTypeMetadata EnumType { get; } @@ -381,14 +452,13 @@ private sealed class GenerateParameters #region Constructors - public GenerateParameters(GeneratorAttributeSyntaxContext context, CSharpParseOptions parseOptions) + public GenerateParameters(GeneratorAttributeSyntaxContext context) { var containerNode = (TypeDeclarationSyntax)context.TargetNode; var containerSymbol = (INamedTypeSymbol)context.TargetSymbol; var enumNode = getEnumNode(containerNode); var enumSymbol = getEnumSymbol(context); - this.LanguageVersion = parseOptions.LanguageVersion; this.FileName = createFileName(containerSymbol); this.ContainerType = new(containerNode, containerSymbol); this.EnumType = new(enumNode, enumSymbol); diff --git a/src/libs/FastEnum.Generators/Internals/EquatableArray.cs b/src/libs/FastEnum.Generators/Internals/EquatableArray.cs new file mode 100644 index 00000000..8a8febe8 --- /dev/null +++ b/src/libs/FastEnum.Generators/Internals/EquatableArray.cs @@ -0,0 +1,80 @@ +using System; +using System.Collections; +using System.Collections.Generic; + +namespace FastEnumUtility.Generators.Internals; + + + +/// +/// Immutable array compared by its elements. +/// +/// +/// The values passed through an incremental generator pipeline are compared with the previous run to decide whether the next steps can be skipped. +/// An array is compared by reference, so it would always look changed; this is compared by value. +/// +internal readonly struct EquatableArray(T[] array) : IEquatable>, IReadOnlyList + where T : IEquatable +{ + #region Fields + private readonly T[]? _array = array; + #endregion + + + #region Properties + private T[] Array + => this._array ?? []; + #endregion + + + #region IEquatable + public bool Equals(EquatableArray other) + { + var x = this.Array; + var y = other.Array; + if (x.Length != y.Length) + return false; + + var comparer = EqualityComparer.Default; + for (var i = 0; i < x.Length; i++) + { + if (!comparer.Equals(x[i], y[i])) + return false; + } + return true; + } + #endregion + + + #region IReadOnlyList + public T this[int index] + => this.Array[index]; + + + public int Count + => this.Array.Length; + + + public IEnumerator GetEnumerator() + => ((IEnumerable)this.Array).GetEnumerator(); + + + IEnumerator IEnumerable.GetEnumerator() + => this.GetEnumerator(); + #endregion + + + #region Overrides + public override bool Equals(object? obj) + => obj is EquatableArray other && this.Equals(other); + + + public override int GetHashCode() + { + var hash = 17; + foreach (var x in this.Array) + hash = (hash * 31) + (x?.GetHashCode() ?? 0); + return hash; + } + #endregion +} diff --git a/src/libs/FastEnum.Generators/Internals/IsExternalInit.cs b/src/libs/FastEnum.Generators/Internals/IsExternalInit.cs new file mode 100644 index 00000000..7e9f67ca --- /dev/null +++ b/src/libs/FastEnum.Generators/Internals/IsExternalInit.cs @@ -0,0 +1,9 @@ +namespace System.Runtime.CompilerServices; + + + +/// +/// Enables init-only setters (and so positional records) on netstandard2.0. +/// +internal static class IsExternalInit +{ }