From a00582a1c7ff4c65065ab6e80794b834894a764f Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Mon, 30 Nov 2026 13:48:18 -0800 Subject: [PATCH] Benchmarks: annotated generated rung, real-database parity and request journey `GenRowDT10` and `GenRowDT20` are the typed twins with every column's ordinal declared, so their generated reader makes the same assumptions as a hand-written selector: constant ordinals, nothing about the result checked. `GenD_T` measures it on the synthetic reader and on the real databases, beside `Gen_T` (the same twin without annotations) and the hand-written controls. `RealParityBenchmarks` compares generated, hand-written and Dapper.AOT reads over SQL Server and SQLite at widths 10 and 20 and 1, 1,000 and 10,000 rows. Its setup compares every rung's rows before timing, and in a counters build requires the generated rungs to be served by generated code. `Gen_T` does not run on SQLite: SQLite stores a `Guid` as text, which the generated reader of an unannotated model leaves to the runtime map, so that rung would have measured the runtime map. `ControllerJourneyBenchmarks` measures query, JSON response and release with `ToArrayAsync`, `ToPooledBuffer` (awaiting `Items` or looping over `AsAsyncEnumerable()`) and `ToPooledBufferStream`, checking every response. Co-Authored-By: Claude Sonnet 5.5 --- .../GeneratedReads.cs | 8 +- .../ControllerJourneyBenchmarks.cs | 297 ++++++++++++++++++ .../RealParityBenchmarks.cs | 126 ++++++++ .../RealProviderBenchmarks.cs | 14 +- .../RealProviderChecks.cs | 9 +- .../RealProviderDapperAot.cs | 3 + .../SyntheticBenchmarks.cs | 5 + .../SyntheticGenerated.cs | 11 +- .../BenchRows.cs | 43 +++ 9 files changed, 508 insertions(+), 8 deletions(-) create mode 100644 Benchmarks/Open.Database.Extensions.Benchmarks/ControllerJourneyBenchmarks.cs create mode 100644 Benchmarks/Open.Database.Extensions.Benchmarks/RealParityBenchmarks.cs diff --git a/Benchmarks/Open.Database.Extensions.Benchmarks.Generated/GeneratedReads.cs b/Benchmarks/Open.Database.Extensions.Benchmarks.Generated/GeneratedReads.cs index 7e58e0c9..9f9977c8 100644 --- a/Benchmarks/Open.Database.Extensions.Benchmarks.Generated/GeneratedReads.cs +++ b/Benchmarks/Open.Database.Extensions.Benchmarks.Generated/GeneratedReads.cs @@ -47,7 +47,13 @@ public static class GeneratedReads /// Gen_T at width 10: as , on the first ten of its members. public static object GenT10(IExecuteReader command) => command.Map().ToList(); - /// How many Map<T>() calls of this assembly the generator intercepted: the methods of its generated interceptor class (12 when it ran). + /// GenD_T: on the decorated twin, so the reader is trusted: constant ordinals, nothing about the result checked. + public static object GenDT20(IExecuteReader command) => command.Map().ToList(); + + /// GenD_T at width 10: as , on the first ten of its members. + public static object GenDT10(IExecuteReader command) => command.Map().ToList(); + + /// How many Map<T>() calls of this assembly the generator intercepted: the methods of its generated interceptor class (14 when it ran). public static int InterceptedCallSites() { foreach (Type type in typeof(GeneratedReads).Assembly.GetTypes()) diff --git a/Benchmarks/Open.Database.Extensions.Benchmarks/ControllerJourneyBenchmarks.cs b/Benchmarks/Open.Database.Extensions.Benchmarks/ControllerJourneyBenchmarks.cs new file mode 100644 index 00000000..5a5e2eb3 --- /dev/null +++ b/Benchmarks/Open.Database.Extensions.Benchmarks/ControllerJourneyBenchmarks.cs @@ -0,0 +1,297 @@ +using System.Buffers; +using System.Data.Common; +using System.Text.Json; +using System.Text.Json.Serialization.Metadata; +using BenchmarkDotNet.Attributes; +using Open.Database.Extensions.Core; + +namespace Open.Database.Extensions.Benchmarks; + +// The controller journey over the synthetic provider: query, write the rows as a +// JSON array with System.Text.Json into a discarding sink, release what was held. +// Run it in process (--inprocess) so the ReaderOpen column is filled (the time +// the connection is held); Mean is the total, dispose included. +// +// ToArray_Json ToArrayAsync (read all, copy into one array), then serialize. +// ToPooledBuffer_Json ToPooledBuffer, await Items (the buffer is not readable while +// it fills), serialize from the pooled chunks, await using. +// ToPooledBuffer_Enumerated_Json ToPooledBuffer, then loop over AsAsyncEnumerable(): +// rows are serialized while the buffer still reads. +// ToPooledBufferStream_Json the overlapped form without a buffer to keep: each chunk is +// serialized while the producer reads on. +// +// All four write each row with the same code, into the same sink. Every operation +// checks the row count, the sum of the Ids and the bytes written against a plain +// ADO read of the same table, so a variant that drops or changes rows fails. +// +// ODX_SYN_ROWS (default 100,1000,10000), ODX_SYN_BUFFER_ROWS and ODX_SYN_REFILL_US +// (default 0: no simulated link), ODX_SYN_ASYNCREADS (default 0: the library's +// default, Read(); 1 turns AsyncReads() on). The width is fixed by the row type. +[MemoryDiagnoser] +[Config(typeof(SyntheticConfig))] +public class ControllerJourneyBenchmarks +{ + const string Sql = SyntheticVariants.Sql; + + // The first nine catalog columns, Id to Note: the members of JourneyRow. + const int Width = 9; + +#pragma warning disable CA2263 // The generic overload it asks for is not on every target framework. + static readonly JsonTypeInfo RowInfo + = (JsonTypeInfo)JsonSerializerOptions.Web.GetTypeInfo(typeof(JourneyRow)); +#pragma warning restore CA2263 + + [ParamsSource(nameof(RowsValues), Priority = 0)] + public int Rows { get; set; } + + [ParamsSource(nameof(BufferRowsValues), Priority = 1)] + public int BufferRows { get; set; } + + [ParamsSource(nameof(RefillUsValues), Priority = 2)] + public int RefillUs { get; set; } + + [ParamsSource(nameof(AsyncReadsValues), Priority = 3)] + public int AsyncReads { get; set; } + + public static IEnumerable RowsValues + => SyntheticParams.Parse( + Environment.GetEnvironmentVariable(SyntheticParams.RowsVariable), + [100, 1000, 10000]); + public static IEnumerable BufferRowsValues => SyntheticParams.BufferRows; + public static IEnumerable RefillUsValues => SyntheticParams.RefillUs; + public static IEnumerable AsyncReadsValues + => SyntheticParams.Parse( + Environment.GetEnvironmentVariable("ODX_SYN_ASYNCREADS"), + [0]); + + SyntheticConnection _connection = null!; + DiscardWriter _sink = null!; + Utf8JsonWriter _json = null!; + long _expectedIdSum; + long _expectedBytes; + long _idSum; + int _count; + string _label = ""; + + [GlobalSetup] + public void Setup() + { + // The pool does not inject threads mid-run: the producer, the + // consumer and the refill continuations need a few from the start. + ThreadPool.GetMinThreads(out int worker, out int io); + ThreadPool.SetMinThreads(Math.Max(worker, 4), io); + + SyntheticTable table = SyntheticTable.Create(Width, Rows); + _connection = new SyntheticConnection( + table, + new SyntheticOptions + { + BufferRows = BufferRows, + RefillCostUs = RefillUs, + }); + + _sink = new DiscardWriter(); + _json = new Utf8JsonWriter(_sink); + Expect(table); + SyntheticIterationListener.Attach(_connection.Options.Recorder); + } + + // What every variant must produce: a plain ADO read of the same table, on its + // own connection (its recorder is not the one the ReaderOpen column reads). + void Expect(SyntheticTable table) + { + using var connection = new SyntheticConnection(table, new SyntheticOptions()); + using DbCommand command = connection.CreateCommand(); + command.CommandText = Sql; + using DbDataReader reader = command.ExecuteReader(); + + Begin(); + while (reader.Read()) + { + Write(new JourneyRow + { + Id = reader.GetInt32(0), + Created = reader.GetDateTime(1), + Title = reader.IsDBNull(2) ? null : reader.GetString(2), + Price = reader.GetDecimal(3), + Qty = reader.IsDBNull(4) ? null : reader.GetInt32(4), + IsActive = reader.GetBoolean(5), + Key = reader.GetGuid(6), + Score = reader.GetDouble(7), + Note = reader.IsDBNull(8) ? null : reader.GetString(8), + }); + } + + _json.WriteEndArray(); + _json.Flush(); + + if (_count != Rows) + throw new InvalidOperationException($"Reference read: {_count} rows, expected {Rows}."); + + _expectedIdSum = _idSum; + _expectedBytes = _sink.Written; + } + + // The label is the method that ran: the recorder's numbers are filed + // under that case, which is what the ReaderOpen column looks up. + [GlobalCleanup] + public void Cleanup() + { + _json.Dispose(); + if (_label.Length == 0) return; + SyntheticBenchmarks.FileResults( + SyntheticBenchmarks.Key( + _label, + [ + (nameof(Rows), Rows), + (nameof(BufferRows), BufferRows), + (nameof(RefillUs), RefillUs), + (nameof(AsyncReads), AsyncReads), + ]), + _connection.Options.Recorder); + } + + [Benchmark(Baseline = true)] + public async ValueTask ToArray_Json() + { + _label = nameof(ToArray_Json); + JourneyRow[] rows = await Command() + .Map() + .ToArrayAsync(CancellationToken.None) + .ConfigureAwait(false); + + Begin(); + foreach (JourneyRow row in rows) + Write(row); + + return End(); + } + + [Benchmark] + public async ValueTask ToPooledBuffer_Json() + { + _label = nameof(ToPooledBuffer_Json); + await using PooledBuffer buffer = Command() + .Map() + .ToPooledBuffer(CancellationToken.None); + + PooledArray rows = await buffer + .Items + .ConfigureAwait(false); + + Begin(); + foreach (JourneyRow row in rows) + Write(row); + + return End(); + } + + [Benchmark] + public async ValueTask ToPooledBuffer_Enumerated_Json() + { + _label = nameof(ToPooledBuffer_Enumerated_Json); + await using PooledBuffer buffer = Command() + .Map() + .ToPooledBuffer(CancellationToken.None); + + Begin(); + await foreach (JourneyRow row in buffer.AsAsyncEnumerable().ConfigureAwait(false)) + Write(row); + + return End(); + } + + [Benchmark] + public async ValueTask ToPooledBufferStream_Json() + { + _label = nameof(ToPooledBufferStream_Json); + Begin(); + await foreach (ReadOnlyMemory chunk in Command() + .Map() + .ToPooledBufferStream(CancellationToken.None) + .ConfigureAwait(false)) + { + WriteChunk(chunk.Span); + } + + return End(); + } + + ExpressiveDbCommand Command() + { + ExpressiveDbCommand command = _connection.Command(Sql); + return AsyncReads != 0 ? command.AsyncReads() : command; + } + + // ----- the response ----- + + void Begin() + { + _sink.Reset(); + _json.Reset(); + _count = 0; + _idSum = 0; + _json.WriteStartArray(); + } + + void Write(JourneyRow row) + { + JsonSerializer.Serialize(_json, row, RowInfo); + _idSum += row.Id; + _count++; + } + + void WriteChunk(ReadOnlySpan rows) + { + foreach (JourneyRow row in rows) + Write(row); + } + + long End() + { + _json.WriteEndArray(); + _json.Flush(); + + return _count == Rows && _idSum == _expectedIdSum && _sink.Written == _expectedBytes + ? _sink.Written + : throw new InvalidOperationException( + $"{_label}: {_count} rows, id sum {_idSum}, {_sink.Written} bytes; expected {Rows}, {_expectedIdSum}, {_expectedBytes}."); + } + + // Counts the bytes and drops them: one reused block, so the sink allocates + // nothing once it is as large as the largest request. + sealed class DiscardWriter : IBufferWriter + { + byte[] _block = new byte[64 * 1024]; + + public long Written { get; private set; } + + public void Reset() => Written = 0; + + public void Advance(int count) => Written += count; + + public Memory GetMemory(int sizeHint = 0) => Block(sizeHint); + + public Span GetSpan(int sizeHint = 0) => Block(sizeHint); + + byte[] Block(int sizeHint) + { + if (sizeHint > _block.Length) _block = new byte[sizeHint]; + return _block; + } + } +} + +// The row of the controller journey: the first nine catalog columns, by name. +public sealed class JourneyRow +{ + public int Id { get; set; } + public DateTime Created { get; set; } + public string? Title { get; set; } + public decimal Price { get; set; } + public int? Qty { get; set; } + public bool IsActive { get; set; } + public Guid Key { get; set; } + public double Score { get; set; } + public string? Note { get; set; } +} diff --git a/Benchmarks/Open.Database.Extensions.Benchmarks/RealParityBenchmarks.cs b/Benchmarks/Open.Database.Extensions.Benchmarks/RealParityBenchmarks.cs new file mode 100644 index 00000000..699f1f0b --- /dev/null +++ b/Benchmarks/Open.Database.Extensions.Benchmarks/RealParityBenchmarks.cs @@ -0,0 +1,126 @@ +using BenchmarkDotNet.Attributes; +using Open.Database.Extensions.Benchmarks.Generated; +using Open.Database.Extensions.Generator.Models; +using Open.Database.Extensions.Synchronous; +using System.Collections; +using System.Reflection; + +namespace Open.Database.Extensions.Benchmarks; + +/// +/// The generated map against the hand-written reader and Dapper.AOT over the real databases, on one row type per width (10 and 20). +/// GenD_T (annotated) and Gen_T (not annotated; SQL Server only) are generated; CtlH_T is the same reads written by hand +/// with the same entry and access mode; V2 is the hand-written selector; V7a_T is Dapper.AOT. +/// Setup reads each once and compares the rows with V2's, so no case is timed over wrong rows. +/// +[MemoryDiagnoser] +[Config(typeof(RealProviderConfig))] +public class RealParityBenchmarks +{ + static readonly int[] DefaultWidths = [10, 20], DefaultRows = [1, 1000, 10_000]; + + [ParamsSource(nameof(ProviderValues), Priority = 0)] + public string Provider { get; set; } = ""; + + [ParamsSource(nameof(WidthValues), Priority = 1)] + public int Width { get; set; } + + [ParamsSource(nameof(RowValues), Priority = 2)] + public int Rows { get; set; } + + public static IEnumerable ProviderValues => RealProviderParams.Providers; + public static IEnumerable WidthValues => SyntheticParams.Parse(Environment.GetEnvironmentVariable(RealProviderParams.WidthsVariable), DefaultWidths); + public static IEnumerable RowValues => SyntheticParams.Parse(Environment.GetEnvironmentVariable(RealProviderParams.RowsVariable), DefaultRows); + + RealProviderCase _case = null!; + Func _hand = null!; + + [GlobalSetup] + public void Setup() + { + if (Width is not (10 or 20)) throw new NotSupportedException($"Row types exist for widths 10 and 20 (this case has width {Width})."); + _case = RealProviderCase.Create(Provider, Width, Rows); + RealProviderVariants.PrepareDapper(Provider); + _hand = SyntheticVariants.Hand(Width); + + List expected = V2(); + if (expected.Count != Rows) throw new InvalidOperationException($"V2 read {expected.Count} rows, expected {Rows}."); + Same(nameof(GenD_T), expected, Generated(nameof(GenD_T), GenD_T)); + Same(nameof(CtlH_T), expected, (IList)CtlH_T()); + Same(nameof(V7a_T), expected, (IList)V7a_T()); + if (Provider == RealProviderParams.SqlServer) Same(nameof(Gen_T), expected, Generated(nameof(Gen_T), Gen_T)); + } + + // Present only in a build with -p:OdxGeneratorCounters=true (never a timed run): then a generated rung must be served by generated code. + static readonly Type? Counters = typeof(GeneratedReads).Assembly.GetType("Open.Database.Extensions.Generated.OdxGeneratedCounters"); + + static long Count(string name) => (long)Counters!.GetField(name)!.GetValue(null)!; + + static IList Generated(string method, Func read) + { + if (Counters is null) return (IList)read(); + + long served = Count("Served"), declined = Count("Declined"); + var rows = (IList)read(); + if (Count("Served") == served || Count("Declined") != declined) + throw new InvalidOperationException($"{method} was not served by generated code: this rung would measure the runtime map."); + + Console.WriteLine($"// REALPARITY {method}: served by generated code"); + return rows; + } + + [GlobalCleanup] + public void Cleanup() + { + if (_case is null) return; + _case.Cleanup(); + Console.WriteLine($"// REALPARITY {Provider} width={Width} rows={Rows}: test data removed, files gone: {_case.FilesGone}"); + } + + // Every property of the row type against the same property of V2's row. + static void Same(string method, List expected, IList actual) + { + if (actual.Count != expected.Count) throw new InvalidOperationException($"{method}: {actual.Count} rows, expected {expected.Count}."); + + for (int i = 0; i < expected.Count; i++) + { + object row = actual[i]!; + foreach (PropertyInfo p in row.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) + { + object? want = typeof(SynRow).GetProperty(p.Name)!.GetValue(expected[i]); + if (!SynRow.Same(want, p.GetValue(row))) throw new InvalidOperationException($"{method}: row {i}, {p.Name} differs from V2."); + } + } + } + + [Benchmark(Baseline = true)] + public List V2() => RealProviderVariants.V2(_case.Timed, _hand); + + [Benchmark] + public object CtlH_T() + => Width == 10 + ? GeneratedControl.ControlHookedT10(_case.Timed.Command(RealProviderVariants.Sql)) + : GeneratedControl.ControlHookedT20(_case.Timed.Command(RealProviderVariants.Sql)); + + [Benchmark] + public object GenD_T() + => Width == 10 + ? GeneratedReads.GenDT10(_case.Timed.Command(RealProviderVariants.Sql)) + : GeneratedReads.GenDT20(_case.Timed.Command(RealProviderVariants.Sql)); + + [Benchmark] + public object Gen_T() + { + // SQLite stores a Guid as text, which the generated reader of an undecorated model leaves to the runtime map. + if (Provider == RealProviderParams.Sqlite) throw new NotSupportedException("Gen_T is not served by generated code on SQLite."); + return Width == 10 + ? GeneratedReads.GenT10(_case.Timed.Command(RealProviderVariants.Sql)) + : GeneratedReads.GenT20(_case.Timed.Command(RealProviderVariants.Sql)); + } + + [Benchmark] + public object V7a_T() + => Width == 10 + ? RealProviderDapperAot.V7aT10(_case.Timed) + : RealProviderDapperAot.V7aT(_case.Timed); +} diff --git a/Benchmarks/Open.Database.Extensions.Benchmarks/RealProviderBenchmarks.cs b/Benchmarks/Open.Database.Extensions.Benchmarks/RealProviderBenchmarks.cs index 1c799aa2..ecb68691 100644 --- a/Benchmarks/Open.Database.Extensions.Benchmarks/RealProviderBenchmarks.cs +++ b/Benchmarks/Open.Database.Extensions.Benchmarks/RealProviderBenchmarks.cs @@ -423,7 +423,19 @@ public void Cleanup() // The generated reader, the hand-written selector of the same row type, and Dapper.AOT building it: all on GenRowT20, whose members have the // table's nullability. Width 20 only (ODX_RP_WIDTHS=20). [Benchmark] - public object Gen_T_Sync() { _label = nameof(Gen_T_Sync); WidthTwenty(); return GeneratedReads.GenT20(Case.Timed.Command(RealProviderVariants.Sql)); } + public object Gen_T_Sync() + { + _label = nameof(Gen_T_Sync); + WidthTwenty(); + + // SQLite stores a Guid as text, which the generated reader of an undecorated model leaves to the runtime map: this rung would measure that. + if (Provider == RealProviderParams.Sqlite) throw new NotSupportedException("Gen_T_Sync is not served by generated code on SQLite; GenD_T_Sync is."); + return GeneratedReads.GenT20(Case.Timed.Command(RealProviderVariants.Sql)); + } + + // GenD_T: the decorated twin, read by the trusted generated reader at constant ordinals. + [Benchmark] + public object GenD_T_Sync() { _label = nameof(GenD_T_Sync); WidthTwenty(); return GeneratedReads.GenDT20(Case.Timed.Command(RealProviderVariants.Sql)); } [Benchmark] public object Ctl_T_Sync() { _label = nameof(Ctl_T_Sync); WidthTwenty(); return GeneratedControl.ControlT20(Case.Timed.Command(RealProviderVariants.Sql)); } diff --git a/Benchmarks/Open.Database.Extensions.Benchmarks/RealProviderChecks.cs b/Benchmarks/Open.Database.Extensions.Benchmarks/RealProviderChecks.cs index 63a8f610..7d438031 100644 --- a/Benchmarks/Open.Database.Extensions.Benchmarks/RealProviderChecks.cs +++ b/Benchmarks/Open.Database.Extensions.Benchmarks/RealProviderChecks.cs @@ -68,7 +68,7 @@ public static int VerifyRealProviders() } if (GeneratorCounters is null) - Console.WriteLine("*** NOT CHECKED: that Gen_T_Sync is served by generated code. Build with -p:OdxGeneratorCounters=true to check it. ***"); + Console.WriteLine("*** NOT CHECKED: that Gen_T_Sync and GenD_T_Sync are served by generated code. Build with -p:OdxGeneratorCounters=true to check it. ***"); string scope = skipped is null ? "both providers" : "SQLite ONLY, SQL SERVER NOT VERIFIED (skipped, see above)"; Console.WriteLine(report.Failures == 0 ? $"VERIFY-RP PASS ({report.Checks} checks; {scope})" : $"VERIFY-RP FAIL ({report.Failures} of {report.Checks} checks failed; {scope})"); @@ -120,9 +120,10 @@ public static int VerifyRealProviders() foreach (var method in typeof(RealProviderBenchmarks).GetMethods().Where(static m => m.GetCustomAttributes(typeof(BenchmarkAttribute), false).Length > 0)) { // The rungs on the 20-column row type run at width 20 only. - if (width != 20 && method.Name is "Gen_T_Sync" or "Ctl_T_Sync" or "V7a_T_Sync") continue; + if (width != 20 && method.Name is "Gen_T_Sync" or "GenD_T_Sync" or "Ctl_T_Sync" or "V7a_T_Sync") continue; + if (provider == RealProviderParams.Sqlite && method.Name == "Gen_T_Sync") continue; // Not a generated rung there (see the method). recorder.Reset(); - bool generated = method.Name == "Gen_T_Sync" && GeneratorCounters is not null; + bool generated = method.Name is "Gen_T_Sync" or "GenD_T_Sync" && GeneratorCounters is not null; long served = generated ? Counter("Served") : 0, declined = generated ? Counter("Declined") : 0; object? result; try { result = method.Invoke(bench, null); } @@ -136,7 +137,7 @@ public static int VerifyRealProviders() if (generated) { report.Check(Counter("Served") > served && Counter("Declined") == declined, - $"Gen_T_Sync {where}: the generated reader did not serve the rows (served {Counter("Served") - served}, declined {Counter("Declined") - declined}): this rung would measure the runtime map"); + $"{method.Name} {where}: the generated reader did not serve the rows (served {Counter("Served") - served}, declined {Counter("Declined") - declined}): this rung would measure the runtime map"); } switch (result) diff --git a/Benchmarks/Open.Database.Extensions.Benchmarks/RealProviderDapperAot.cs b/Benchmarks/Open.Database.Extensions.Benchmarks/RealProviderDapperAot.cs index 64ff8eb8..29cb467a 100644 --- a/Benchmarks/Open.Database.Extensions.Benchmarks/RealProviderDapperAot.cs +++ b/Benchmarks/Open.Database.Extensions.Benchmarks/RealProviderDapperAot.cs @@ -16,4 +16,7 @@ public static class RealProviderDapperAot /// The same call building the generated rung's row type (); width 20. public static List V7aT(DbConnection connection) => connection.Query(RealProviderVariants.Sql).AsList(); + + /// at width 10, building . + public static List V7aT10(DbConnection connection) => connection.Query(RealProviderVariants.Sql).AsList(); } diff --git a/Benchmarks/Open.Database.Extensions.Benchmarks/SyntheticBenchmarks.cs b/Benchmarks/Open.Database.Extensions.Benchmarks/SyntheticBenchmarks.cs index e71ed9fa..a359c18b 100644 --- a/Benchmarks/Open.Database.Extensions.Benchmarks/SyntheticBenchmarks.cs +++ b/Benchmarks/Open.Database.Extensions.Benchmarks/SyntheticBenchmarks.cs @@ -349,6 +349,11 @@ void WidthTwenty() [Benchmark] public object Gen_T_Sync() { _label = nameof(Gen_T_Sync); TenOrTwenty(); return SyntheticGenerated.GenT(Connection, Width); } + // GenD_T: Gen_T's twin decorated, so its reader is trusted (constant ordinals, no look at the result), the assumptions a hand-written selector makes. + // Its bar is CtlH_T; Gen_T beside it shows what the per-result-set name and type check of an undecorated model costs. + [Benchmark] + public object GenD_T_Sync() { _label = nameof(GenD_T_Sync); TenOrTwenty(); return SyntheticGenerated.GenDT(Connection, Width); } + [Benchmark] public object Ctl_T_Sync() { _label = nameof(Ctl_T_Sync); TenOrTwenty(); return SyntheticGenerated.CtlT(Connection, Width); } diff --git a/Benchmarks/Open.Database.Extensions.Benchmarks/SyntheticGenerated.cs b/Benchmarks/Open.Database.Extensions.Benchmarks/SyntheticGenerated.cs index fef3d7cf..5d36ce6d 100644 --- a/Benchmarks/Open.Database.Extensions.Benchmarks/SyntheticGenerated.cs +++ b/Benchmarks/Open.Database.Extensions.Benchmarks/SyntheticGenerated.cs @@ -37,6 +37,12 @@ public static object GenT(SyntheticConnection connection, int width) ? GeneratedReads.GenT10(connection.Command(SyntheticVariants.Sql)) : GeneratedReads.GenT20(connection.Command(SyntheticVariants.Sql)); + /// GenD_T (widths 10 and 20): Gen_T's twin decorated, read by the trusted generated reader. Its bar is CtlH_T: hand-written reads, same entry. + public static object GenDT(SyntheticConnection connection, int width) + => width == 10 + ? GeneratedReads.GenDT10(connection.Command(SyntheticVariants.Sql)) + : GeneratedReads.GenDT20(connection.Command(SyntheticVariants.Sql)); + /// The control of Gen_T: the hand-written selector of Gen_T's twin, compiled beside it; its reads are V2's Read20 cell for cell (only the row type differs). public static object CtlT(SyntheticConnection connection, int width) => width == 10 @@ -94,7 +100,7 @@ public static partial class SyntheticChecks static void VerifyGenerated(Report report, SyntheticConnection conn, int width, List v2, string where) { int sites = GeneratedReads.InterceptedCallSites(); - report.Check(sites == 12, $"Gen/GenD: {sites} intercepted call sites, expected the 12 of GeneratedReads (is the generator referenced there?)"); + report.Check(sites == 14, $"Gen/GenD: {sites} intercepted call sites, expected the 14 of GeneratedReads (is the generator referenced there?)"); // And none here: V1 (the baseline) and every other runtime variant of this project stay the runtime map. bool interceptedHere = typeof(SyntheticChecks).Assembly.GetTypes().Any(static t => t.Name.EndsWith("OdxInterceptors", StringComparison.Ordinal)); @@ -106,6 +112,7 @@ static void VerifyGenerated(Report report, SyntheticConnection conn, int width, if (HasTypedTwin(width)) { CompareGenerated(report, "Gen_T vs V2", where, v2, (IList)SyntheticGenerated.GenT(conn, width)); + CompareGenerated(report, "GenD_T vs V2", where, v2, (IList)SyntheticGenerated.GenDT(conn, width)); CompareGenerated(report, "Ctl_T vs V2", where, v2, (IList)SyntheticGenerated.CtlT(conn, width)); CompareGenerated(report, "CtlH_T vs V2", where, v2, (IList)SyntheticGenerated.CtlHT(conn, width)); CompareGenerated(report, "V7a_T vs V2", where, v2, (IList)SyntheticDapperAot.T(conn, width)); @@ -149,7 +156,7 @@ static bool HasDapperAotReader(Type row) static bool HasTypedTwin(int width) => width is 10 or 20; // Gen_T, its controls and Dapper.AOT on the same twin: widths 10 and 20. - static bool TypedTwinOnly(string method) => method is "Gen_T_Sync" or "Ctl_T_Sync" or "CtlH_T_Sync" or "V7a_T_Sync"; + static bool TypedTwinOnly(string method) => method is "Gen_T_Sync" or "GenD_T_Sync" or "Ctl_T_Sync" or "CtlH_T_Sync" or "V7a_T_Sync"; // The NULL policy twins (SynRowPolicy.cs) against V1, member by member. A narrower table has no column for some members: SynRow leaves a reference-typed // one null, a twin keeps its initializer ("" or an empty array). That tolerance holds ONLY for a member whose column is missing from the table (not in diff --git a/Tests/Open.Database.Extensions.Generator.Models/BenchRows.cs b/Tests/Open.Database.Extensions.Generator.Models/BenchRows.cs index d39bae0d..95897d62 100644 --- a/Tests/Open.Database.Extensions.Generator.Models/BenchRows.cs +++ b/Tests/Open.Database.Extensions.Generator.Models/BenchRows.cs @@ -185,4 +185,47 @@ public sealed class GenRowT20 public string? Summary { get; set; } } +/// decorated: every member declares its column and ordinal, so its generated reader is trusted. +public sealed class GenRowDT10 +{ + [Column("Id", Order = 0)] public int Id { get; set; } + [Column("Created", Order = 1)] public DateTime Created { get; set; } + [Column("Title", Order = 2)] public string Title { get; set; } + [Column("Price", Order = 3)] public decimal Price { get; set; } + [Column("Qty", Order = 4)] public int? Qty { get; set; } + [Column("IsActive", Order = 5)] public bool IsActive { get; set; } + [Column("Key", Order = 6)] public Guid Key { get; set; } + [Column("Score", Order = 7)] public double Score { get; set; } + [Column("Note", Order = 8)] public string? Note { get; set; } + [Column("Blob", Order = 9)] public byte[] Blob { get; set; } +} + +/// +/// decorated (GenD_T): the member types V2's selector assumes, every ordinal declared, so the generated reader reads the same +/// cells the same way at constant ordinals and looks at nothing else: the same assumptions as a hand-written selector. +/// +public sealed class GenRowDT20 +{ + [Column("Id", Order = 0)] public int Id { get; set; } + [Column("Created", Order = 1)] public DateTime Created { get; set; } + [Column("Title", Order = 2)] public string Title { get; set; } + [Column("Price", Order = 3)] public decimal Price { get; set; } + [Column("Qty", Order = 4)] public int? Qty { get; set; } + [Column("IsActive", Order = 5)] public bool IsActive { get; set; } + [Column("Key", Order = 6)] public Guid Key { get; set; } + [Column("Score", Order = 7)] public double Score { get; set; } + [Column("Note", Order = 8)] public string? Note { get; set; } + [Column("Blob", Order = 9)] public byte[] Blob { get; set; } + [Column("Big", Order = 10)] public long Big { get; set; } + [Column("Body", Order = 11)] public string Body { get; set; } + [Column("Amount", Order = 12)] public decimal? Amount { get; set; } + [Column("Stamp", Order = 13)] public DateTime? Stamp { get; set; } + [Column("Tag", Order = 14)] public string Tag { get; set; } + [Column("Ratio", Order = 15)] public double Ratio { get; set; } + [Column("Flag", Order = 16)] public bool? Flag { get; set; } + [Column("Link", Order = 17)] public Guid? Link { get; set; } + [Column("Count", Order = 18)] public long Count { get; set; } + [Column("Summary", Order = 19)] public string? Summary { get; set; } +} + #pragma warning restore CS8618