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
Expand Up @@ -47,7 +47,13 @@ public static class GeneratedReads
/// <summary>Gen_T at width 10: as <see cref="GenT20"/>, on the first ten of its members.</summary>
public static object GenT10(IExecuteReader command) => command.Map<GenRowT10>().ToList();

/// <summary>How many Map&lt;T&gt;() calls of this assembly the generator intercepted: the methods of its generated interceptor class (12 when it ran).</summary>
/// <summary>GenD_T: <see cref="GenT20"/> on the decorated twin, so the reader is trusted: constant ordinals, nothing about the result checked.</summary>
public static object GenDT20(IExecuteReader command) => command.Map<GenRowDT20>().ToList();

/// <summary>GenD_T at width 10: as <see cref="GenDT20"/>, on the first ten of its members.</summary>
public static object GenDT10(IExecuteReader command) => command.Map<GenRowDT10>().ToList();

/// <summary>How many Map&lt;T&gt;() calls of this assembly the generator intercepted: the methods of its generated interceptor class (14 when it ran).</summary>
public static int InterceptedCallSites()
{
foreach (Type type in typeof(GeneratedReads).Assembly.GetTypes())
Expand Down
Original file line number Diff line number Diff line change
@@ -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<JourneyRow> RowInfo
= (JsonTypeInfo<JourneyRow>)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<int> RowsValues
=> SyntheticParams.Parse(
Environment.GetEnvironmentVariable(SyntheticParams.RowsVariable),
[100, 1000, 10000]);
public static IEnumerable<int> BufferRowsValues => SyntheticParams.BufferRows;
public static IEnumerable<int> RefillUsValues => SyntheticParams.RefillUs;
public static IEnumerable<int> 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<long> ToArray_Json()
{
_label = nameof(ToArray_Json);
JourneyRow[] rows = await Command()
.Map<JourneyRow>()
.ToArrayAsync(CancellationToken.None)
.ConfigureAwait(false);

Begin();
foreach (JourneyRow row in rows)
Write(row);

return End();
}

[Benchmark]
public async ValueTask<long> ToPooledBuffer_Json()
{
_label = nameof(ToPooledBuffer_Json);
await using PooledBuffer<JourneyRow> buffer = Command()
.Map<JourneyRow>()
.ToPooledBuffer(CancellationToken.None);

PooledArray<JourneyRow> rows = await buffer
.Items
.ConfigureAwait(false);

Begin();
foreach (JourneyRow row in rows)
Write(row);

return End();
}

[Benchmark]
public async ValueTask<long> ToPooledBuffer_Enumerated_Json()
{
_label = nameof(ToPooledBuffer_Enumerated_Json);
await using PooledBuffer<JourneyRow> buffer = Command()
.Map<JourneyRow>()
.ToPooledBuffer(CancellationToken.None);

Begin();
await foreach (JourneyRow row in buffer.AsAsyncEnumerable().ConfigureAwait(false))
Write(row);

return End();
}

[Benchmark]
public async ValueTask<long> ToPooledBufferStream_Json()
{
_label = nameof(ToPooledBufferStream_Json);
Begin();
await foreach (ReadOnlyMemory<JourneyRow> chunk in Command()
.Map<JourneyRow>()
.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<JourneyRow> 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>
{
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<byte> GetMemory(int sizeHint = 0) => Block(sizeHint);

public Span<byte> 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; }
}
Loading