Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using Open.Database.Extensions.Synchronous;

namespace Open.Database.Extensions.Benchmarks.Generated;

/// <summary>The ODX rungs of the single-value gate table: column 0 of every row.</summary>
public static class SingleValueReads
{
/// <summary>The hand-written selector.</summary>
public static List<int> Hand(IExecuteReader command)
=> command.Map(static r => r.GetInt32(0)).ToList();

/// <summary>The A/A control: the same selector, compiled as a method of its own.</summary>
public static List<int> HandCopy(IExecuteReader command)
=> command.Map(static r => r.GetInt32(0)).ToList();

/// <summary><c>Map&lt;int&gt;()</c> as shipped: the generator declines a single value, so the runtime map reads it.</summary>
public static List<int> Shipped(IExecuteReader command)
=> command.Map<int>().ToList();
}
170 changes: 141 additions & 29 deletions Benchmarks/Open.Database.Extensions.Benchmarks/GateBenchmarks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ namespace Open.Database.Extensions.Benchmarks;
// Gen_T the generated reader of the unannotated model
// Selector the selector a caller writes, Map(selector)
// Dapper.AOT and Dapper: in both tables; unforced in the sequential one (their own mode), forced in the default one and labelled so.
// RawAdo_T reference, not gated: plain ADO.NET with no library (RawAdoReads). What it takes less than CtlH_T is the library's own cost.
//
// GateSingleValueBenchmarks is the third table, default access: column 0 of every row (Map of one value), over the same sources and row counts.
//
// Every rung, forced or not, reads through ReadModeConnection (benchmarks only; library defaults are unchanged), so no rung pays a layer
// another does not, and setup checks the mode its rung read in. No gate table holds a cross-mode ratio; what the mode itself costs is
Expand Down Expand Up @@ -58,22 +61,29 @@ public static int Verify()
{
foreach (int rows in GateShapes.RowValues)
{
Run(new GateDefaultAccessBenchmarks());
Run(new GateSequentialAccessBenchmarks());
Run(new ReadModeEffectBenchmarks { Generated = false });
Run(new ReadModeEffectBenchmarks { Generated = true });
Run(new GateDefaultAccessBenchmarks { Width = width });
Run(new GateSequentialAccessBenchmarks { Width = width });
Run(new ReadModeEffectBenchmarks { Width = width, Generated = false });
Run(new ReadModeEffectBenchmarks { Width = width, Generated = true });

void Run(GateShapes gate)
{
gate.Source = source;
gate.Width = width;
gate.Rows = rows;
gate.VerifyAll();
gate.Cleanup();
cases++;
}
}
}

foreach (int rows in GateShapes.RowValues)
{
var single = new GateSingleValueBenchmarks { Source = source, Rows = rows };
single.VerifyAll();
single.Cleanup();
cases++;
}
}

Console.WriteLine($"// GATE-VERIFY {cases} cases: every rung read the right rows in its table's mode.");
Expand Down Expand Up @@ -130,22 +140,17 @@ .. benchmarksCase
}
}

/// <summary>The case every gate table shares: where the rows come from, how wide and how many.</summary>
public abstract class GateShapes
/// <summary>What every gate table shares: where the rows come from and how many.</summary>
public abstract class GateSource
{
public const string Synthetic = "Synthetic";

[ParamsSource(nameof(SourceValues), Priority = 0)]
public string Source { 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<int> WidthValues => SyntheticParams.Parse(Environment.GetEnvironmentVariable("ODX_GATE_WIDTHS"), [10, 20]);

public static IEnumerable<int> RowValues => SyntheticParams.Parse(Environment.GetEnvironmentVariable("ODX_GATE_ROWS"), [1, 1000, 10_000]);

public static IEnumerable<string> SourceValues
Expand All @@ -155,38 +160,34 @@ public static IEnumerable<string> SourceValues

RealProviderCase? _case;
DbConnection _connection = null!;
List<SynRow> _expected = null!;

protected void Open()
protected void Connect(int width)
{
if (Source == Synthetic)
{
_connection = new SyntheticConnection(SyntheticTable.Create(Width, Rows), new SyntheticOptions());
_connection = new SyntheticConnection(SyntheticTable.Create(width, Rows), new SyntheticOptions());
RealProviderVariants.PrepareDapper(RealProviderParams.SqlServer); // No type handlers.
}
else
{
_case = RealProviderCase.Create(Source, Width, Rows);
_case = RealProviderCase.Create(Source, width, Rows);
_connection = _case.Real;
RealProviderVariants.PrepareDapper(Source);
}

// The oracle, read with plain ADO.NET: a process times one rung, and no other reading may go through the library's shared read loop first.
_expected = Oracle();
if (_expected.Count != Rows) throw new InvalidOperationException($"{_expected.Count} rows, expected {Rows}.");

// One line per process in the log: which case it ran.
Console.WriteLine($"// GATE-PID {Environment.ProcessId} {System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription} {GetType().Name} {Source} width={Width} rows={Rows}");
Console.WriteLine($"// GATE-PID {Environment.ProcessId} {System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription} {GetType().Name} {Source} width={width} rows={Rows}");
}

List<SynRow> Oracle()
// The oracle, read with plain ADO.NET: a process times one rung, and no other reading may go through the library's shared read loop first.
protected List<T> Oracle<T>(Func<IDataRecord, T> hand)
{
Func<IDataRecord, SynRow> hand = SyntheticVariants.Hand(Width);
using DbCommand command = _connection.CreateCommand();
command.CommandText = RealProviderVariants.Sql;
using DbDataReader reader = command.ExecuteReader();
var rows = new List<SynRow>();
var rows = new List<T>();
while (reader.Read()) rows.Add(hand(reader));
if (rows.Count != Rows) throw new InvalidOperationException($"{rows.Count} rows, expected {Rows}.");
return rows;
}

Expand All @@ -196,18 +197,41 @@ List<SynRow> Oracle()
/// <summary>The case's connection in the given read mode; <see langword="null"/> leaves each reader as its caller asks.</summary>
protected ReadModeConnection In(bool? sequential) => new(_connection, sequential);

// No case is timed over wrong rows or in another read mode than its table's; in a counters build a generated rung must be served by generated code.
protected void Check(string rung, ReadModeConnection connection, bool sequential, Func<object> read, bool generated = false)
// No case is timed in another read mode than its table's.
protected static void CheckMode(string rung, ReadModeConnection connection, bool sequential)
{
connection.Reset();
IList rows = generated ? RealParityBenchmarks.Generated(rung, read) : (IList)read();
if (connection.Last is not { } used || used.HasFlag(CommandBehavior.SequentialAccess) != sequential)
throw new InvalidOperationException($"{rung} read with {connection.Last}, not in its table's mode.");
RealParityBenchmarks.Same(rung, _expected, rows);
}

[GlobalCleanup]
public void Cleanup() => _case?.Cleanup();
}

/// <summary>A gate table of typed rows: how wide they are.</summary>
public abstract class GateShapes : GateSource
{
[ParamsSource(nameof(WidthValues), Priority = 1)]
public int Width { get; set; }

public static IEnumerable<int> WidthValues => SyntheticParams.Parse(Environment.GetEnvironmentVariable("ODX_GATE_WIDTHS"), [10, 20]);

List<SynRow> _expected = null!;

protected void Open()
{
Connect(Width);
_expected = Oracle(SyntheticVariants.Hand(Width));
}

// No case is timed over wrong rows or in another read mode than its table's; in a counters build a generated rung must be served by generated code.
protected void Check(string rung, ReadModeConnection connection, bool sequential, Func<object> read, bool generated = false)
{
connection.Reset();
IList rows = generated ? RealParityBenchmarks.Generated(rung, read) : (IList)read();
CheckMode(rung, connection, sequential);
RealParityBenchmarks.Same(rung, _expected, rows);
}

static ExpressiveDbCommand Command(ReadModeConnection connection) => connection.Command(RealProviderVariants.Sql);

Expand Down Expand Up @@ -253,8 +277,12 @@ public override void VerifyAll()
CheckRung(nameof(GenD_T), GenD_T, generated: true);
CheckRung(nameof(Gen_T), Gen_T, generated: true);
CheckRung(nameof(Selector), Selector);
CheckRung(nameof(RawAdo_T), RawAdo_T);
}

[GlobalSetup(Target = nameof(RawAdo_T))]
public void SetupRawAdo_T() { Prepare(); CheckRung(nameof(RawAdo_T), RawAdo_T); }

[GlobalSetup(Target = nameof(CtlH_T))]
public void SetupCtlH_T() { Prepare(); CheckRung(nameof(CtlH_T), CtlH_T); }

Expand Down Expand Up @@ -285,6 +313,13 @@ public override void VerifyAll()
[Benchmark]
public object Selector() => Written(_mode);

[Benchmark(Description = "RawAdo_T (reference, not gated)")]
public object RawAdo_T()
{
CommandBehavior behavior = Sequential ? CommandBehavior.SequentialAccess : CommandBehavior.Default;
return Width == 10 ? RawAdoReads.T10(_mode, behavior) : RawAdoReads.T20(_mode, behavior);
}

protected object ReadDapperAot(ReadModeConnection c) => Width == 10 ? RealProviderDapperAot.V7aT10(c) : RealProviderDapperAot.V7aT(c);

protected object ReadDapper(ReadModeConnection c) => RealProviderVariants.V7T(c, Width);
Expand Down Expand Up @@ -362,6 +397,83 @@ public override void VerifyAll()
public object Dapper() => ReadDapper(_own);
}

/// <summary>
/// The single-value table, default access: column 0 of every row of the width-10 result. The baseline is the hand-written selector, with its
/// A/A copy; <c>Map&lt;int&gt;()</c> is what the library ships for a single value (the generator declines it). Dapper.AOT and Dapper are forced
/// into default access, as in the default table. Each timed process sets up and checks only its own rung.
/// </summary>
[MemoryDiagnoser]
[Config(typeof(GateConfig))]
public class GateSingleValueBenchmarks : GateSource
{
const int ResultWidth = 10;

ReadModeConnection _mode = null!;
List<int> _expected = null!;

void Prepare()
{
Connect(ResultWidth);
_expected = Oracle(static r => r.GetInt32(0));
_mode = In(false);
}

void CheckRung(string rung, Func<List<int>> read)
{
_mode.Reset();
List<int> values = read();
CheckMode(rung, _mode, sequential: false);
if (!values.SequenceEqual(_expected)) throw new InvalidOperationException($"{rung}: the values differ from plain ADO.NET.");
}

public override void VerifyAll()
{
Prepare();
CheckRung(nameof(CtlH), CtlH);
CheckRung(nameof(CtlH2), CtlH2);
CheckRung(nameof(MapScalar), MapScalar);
CheckRung(nameof(RawAdo), RawAdo);
CheckRung(nameof(DapperAot), DapperAot);
CheckRung(nameof(Dapper), Dapper);
}

[GlobalSetup(Target = nameof(CtlH))]
public void SetupCtlH() { Prepare(); CheckRung(nameof(CtlH), CtlH); }

[GlobalSetup(Target = nameof(CtlH2))]
public void SetupCtlH2() { Prepare(); CheckRung(nameof(CtlH2), CtlH2); }

[GlobalSetup(Target = nameof(MapScalar))]
public void SetupMapScalar() { Prepare(); CheckRung(nameof(MapScalar), MapScalar); }

[GlobalSetup(Target = nameof(RawAdo))]
public void SetupRawAdo() { Prepare(); CheckRung(nameof(RawAdo), RawAdo); }

[GlobalSetup(Target = nameof(DapperAot))]
public void SetupDapperAot() { Prepare(); CheckRung(nameof(DapperAot), DapperAot); }

[GlobalSetup(Target = nameof(Dapper))]
public void SetupDapper() { Prepare(); CheckRung(nameof(Dapper), Dapper); }

[Benchmark(Baseline = true)]
public List<int> CtlH() => SingleValueReads.Hand(_mode.Command(RealProviderVariants.Sql));

[Benchmark]
public List<int> CtlH2() => SingleValueReads.HandCopy(_mode.Command(RealProviderVariants.Sql));

[Benchmark(Description = "Map<int>()")]
public List<int> MapScalar() => SingleValueReads.Shipped(_mode.Command(RealProviderVariants.Sql));

[Benchmark(Description = "RawAdo (reference, not gated)")]
public List<int> RawAdo() => RawAdoReads.Values(_mode);

[Benchmark(Description = "Dapper.AOT (forced)")]
public List<int> DapperAot() => RealProviderDapperAot.V7aValues(_mode);

[Benchmark(Description = "Dapper (forced)")]
public List<int> Dapper() => RealProviderVariants.V7Values(_mode);
}

/// <summary>What the read mode itself costs, path by path: default access against sequential, the same reader code.</summary>
[MemoryDiagnoser]
[Config(typeof(GateConfig))]
Expand Down
89 changes: 89 additions & 0 deletions Benchmarks/Open.Database.Extensions.Benchmarks/RawAdoReads.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
using Open.Database.Extensions.Generator.Models;
using System.Data;
using System.Data.Common;

namespace Open.Database.Extensions.Benchmarks;

/// <summary>
/// Plain ADO.NET, no library: the gate's reference rung (not gated). The same work as an ODX rung does around its row reader: create the command,
/// open the reader in the table's mode, list every row at constant ordinals, read through any later result set, dispose.
/// What it takes less than the hand-written rung is the library's own cost.
/// </summary>
public static class RawAdoReads
{
public static List<GenRowT10> T10(DbConnection connection, CommandBehavior behavior)
{
using DbCommand command = connection.CreateCommand();
command.CommandText = RealProviderVariants.Sql;
using DbDataReader r = command.ExecuteReader(behavior);
var list = new List<GenRowT10>();
while (r.Read())
{
list.Add(new()
{
Id = r.GetInt32(0),
Created = r.GetDateTime(1),
Title = r.GetString(2),
Price = r.GetDecimal(3),
Qty = r.IsDBNull(4) ? null : r.GetInt32(4),
IsActive = r.GetBoolean(5),
Key = r.GetGuid(6),
Score = r.GetDouble(7),
Note = r.IsDBNull(8) ? null : r.GetString(8),
Blob = (byte[])r.GetValue(9),
});
}

while (r.NextResult()) { }
return list;
}

public static List<GenRowT20> T20(DbConnection connection, CommandBehavior behavior)
{
using DbCommand command = connection.CreateCommand();
command.CommandText = RealProviderVariants.Sql;
using DbDataReader r = command.ExecuteReader(behavior);
var list = new List<GenRowT20>();
while (r.Read())
{
list.Add(new()
{
Id = r.GetInt32(0),
Created = r.GetDateTime(1),
Title = r.GetString(2),
Price = r.GetDecimal(3),
Qty = r.IsDBNull(4) ? null : r.GetInt32(4),
IsActive = r.GetBoolean(5),
Key = r.GetGuid(6),
Score = r.GetDouble(7),
Note = r.IsDBNull(8) ? null : r.GetString(8),
Blob = (byte[])r.GetValue(9),
Big = r.GetInt64(10),
Body = r.GetString(11),
Amount = r.IsDBNull(12) ? null : r.GetDecimal(12),
Stamp = r.IsDBNull(13) ? null : r.GetDateTime(13),
Tag = r.GetString(14),
Ratio = r.GetDouble(15),
Flag = r.IsDBNull(16) ? null : r.GetBoolean(16),
Link = r.IsDBNull(17) ? null : r.GetGuid(17),
Count = r.GetInt64(18),
Summary = r.IsDBNull(19) ? null : r.GetString(19),
});
}

while (r.NextResult()) { }
return list;
}

/// <summary>The single-value table's reference rung: column 0 of every row.</summary>
public static List<int> Values(DbConnection connection)
{
using DbCommand command = connection.CreateCommand();
command.CommandText = RealProviderVariants.Sql;
using DbDataReader r = command.ExecuteReader(CommandBehavior.Default);
var list = new List<int>();
while (r.Read()) list.Add(r.GetInt32(0));
while (r.NextResult()) { }
return list;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,7 @@ public static class RealProviderDapperAot

/// <summary><see cref="V7aT"/> at width 10, building <see cref="GenRowT10"/>.</summary>
public static List<GenRowT10> V7aT10(DbConnection connection) => connection.Query<GenRowT10>(RealProviderVariants.Sql).AsList();

/// <summary>The single-value gate table's call: column 0 of every row.</summary>
public static List<int> V7aValues(DbConnection connection) => connection.Query<int>(RealProviderVariants.Sql).AsList();
}
Loading