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 @@ -6,8 +6,8 @@ namespace Open.Database.Extensions.Tests;

// Bytes per call of the reader's ToArrayAsync and ToImmutableArrayAsync (pooled chunks, one copy)
// against the same rows read into an ImmutableArray.Builder whose capacity is not known.
// A count of bytes, not a time. The reader is an in-memory DataTableReader, whose
// ReadAsync finishes at once and allocates nothing, so a thread-local counter sees everything.
// A count of bytes, not a time. The reader is an in-memory reader of one int column (Int32ColumnReader), whose
// ReadAsync finishes at once and whose typed getter allocates nothing, so a thread-local counter sees everything.
// The read alone is measured too, so that what the rows themselves cost can be taken off.
// Run it by itself, in Release: dotnet test --filter-method "*Probe_BytesPerCall" with the Explicit run option.
[ExcludeFromCodeCoverage]
Expand All @@ -16,25 +16,17 @@ public sealed class ReaderCollectAllocationProbe(ITestOutputHelper output)
{
const int Rounds = 15;

static DataTable Table(int rows)
{
var table = new DataTable();
table.Columns.Add("Id", typeof(int));
for (int i = 0; i < rows; i++) table.Rows.Add(i);
return table;
}

static ValueTask<int> Id(IDataRecord r) => new(r.GetInt32(0));

// The smallest of several runs, each with a new reader made before the count starts.
static async Task<long> Measure(DataTable table, Func<DbDataReader, Task> call)
static async Task<long> Measure(Int32Column column, Func<DbDataReader, Task> call)
{
for (int i = 0; i < 20; i++) await call(table.CreateDataReader());
for (int i = 0; i < 20; i++) await call(new Int32ColumnReader(column));

long best = long.MaxValue;
for (int i = 0; i < Rounds; i++)
{
DbDataReader reader = table.CreateDataReader();
DbDataReader reader = new Int32ColumnReader(column);
GC.Collect();
GC.WaitForPendingFinalizers();
long before = GC.GetAllocatedBytesForCurrentThread();
Expand All @@ -52,11 +44,11 @@ static async Task<long> Measure(DataTable table, Func<DbDataReader, Task> call)
[InlineData(100_000)]
public async Task ToImmutableArrayAsync_AllocatesLessThanABuilderOfUnknownCapacity(int rows)
{
DataTable table = Table(rows);
Int32Column column = Int32Column.Of(rows);

long chain = await Measure(table, async r
long chain = await Measure(column, async r
=> GC.KeepAlive(await r.ToImmutableArrayAsync(Id, TestContext.Current.CancellationToken)));
long builder = await Measure(table, async r =>
long builder = await Measure(column, async r =>
{
ImmutableArray<int>.Builder b = ImmutableArray.CreateBuilder<int>();
while (await r.ReadAsync(TestContext.Current.CancellationToken)) b.Add(r.GetInt32(0));
Expand All @@ -73,25 +65,25 @@ public async Task Probe_BytesPerCall()
output.WriteLine("rows | read alone | ToImmutableArrayAsync | builder + ToImmutable | ToArrayAsync | List + ToArray | (bytes; net of the read alone in the next line)");
foreach (int rows in new[] { 0, 1, 1000, 100_000 })
{
DataTable table = Table(rows);
Int32Column column = Int32Column.Of(rows);

long read = await Measure(table, async r =>
long read = await Measure(column, async r =>
{
int sum = 0;
while (await r.ReadAsync(TestContext.Current.CancellationToken)) sum += r.GetInt32(0);
GC.KeepAlive(sum);
});
long chain = await Measure(table, async r
long chain = await Measure(column, async r
=> GC.KeepAlive(await r.ToImmutableArrayAsync(Id, TestContext.Current.CancellationToken)));
long builder = await Measure(table, async r =>
long builder = await Measure(column, async r =>
{
ImmutableArray<int>.Builder b = ImmutableArray.CreateBuilder<int>();
while (await r.ReadAsync(TestContext.Current.CancellationToken)) b.Add(r.GetInt32(0));
GC.KeepAlive(b.ToImmutable());
});
long array = await Measure(table, async r
long array = await Measure(column, async r
=> GC.KeepAlive(await r.ToArrayAsync(Id, TestContext.Current.CancellationToken)));
long list = await Measure(table, async r =>
long list = await Measure(column, async r =>
{
var l = new List<int>();
while (await r.ReadAsync(TestContext.Current.CancellationToken)) l.Add(r.GetInt32(0));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ namespace Open.Database.Extensions.Tests;

#nullable enable

// Bytes per call of the synchronous ToList of a mapped view, over an in-memory DataTable,
// against a List that grows (the old shape, written by hand over a DataTableReader).
// Bytes per call of the synchronous ToList of a mapped view, over an in-memory reader of one int column,
// against a List that grows (the old shape, written by hand over the same reader).
// The reader's typed getter allocates nothing (see Int32ColumnReader): a DataTableReader boxes each value
// until the JIT has optimized the read, which made this a race with the JIT's tier-up.
// A count of bytes, not a time; the thread-local counter sees everything because nothing suspends.
// Run it by itself, in Release, with the test executable and -explicit only.
[ExcludeFromCodeCoverage]
Expand All @@ -12,14 +14,6 @@ public sealed class SyncToListAllocationProbe(ITestOutputHelper output)
{
const int Rounds = 15;

static DataTable Table(int rows)
{
var table = new DataTable();
table.Columns.Add("Id", typeof(int));
for (int i = 0; i < rows; i++) table.Rows.Add(i);
return table;
}

// The smallest of several runs, after a warm-up.
static long Measure(Action call)
{
Expand All @@ -45,12 +39,12 @@ static long Measure(Action call)
[InlineData(100_000)]
public void ToList_AllocatesLessThanAListThatGrows(int rows)
{
DataTable table = Table(rows);
Int32Column column = Int32Column.Of(rows);

long chain = Measure(() => GC.KeepAlive(table.Map<int>().ToList()));
long chain = Measure(() => GC.KeepAlive(new Int32ColumnReader(column).Map<int>().ToList()));
long grows = Measure(() =>
{
using DataTableReader r = table.CreateDataReader();
using var r = new Int32ColumnReader(column);
var l = new List<int>();
while (r.Read()) l.Add(r.GetInt32(0));
GC.KeepAlive(l);
Expand All @@ -66,17 +60,17 @@ public void Probe_BytesPerCall()
output.WriteLine("rows | view.ToList() | List that grows (by hand) | view.ToArray() (bytes per call)");
foreach (int rows in new[] { 0, 1, 1000, 100_000 })
{
DataTable table = Table(rows);
Int32Column column = Int32Column.Of(rows);

long list = Measure(() => GC.KeepAlive(table.Map<int>().ToList()));
long list = Measure(() => GC.KeepAlive(new Int32ColumnReader(column).Map<int>().ToList()));
long grows = Measure(() =>
{
using DataTableReader r = table.CreateDataReader();
using var r = new Int32ColumnReader(column);
var l = new List<int>();
while (r.Read()) l.Add(r.GetInt32(0));
GC.KeepAlive(l);
});
long array = Measure(() => GC.KeepAlive(table.Map<int>().ToArray()));
long array = Measure(() => GC.KeepAlive(new Int32ColumnReader(column).Map<int>().ToArray()));

output.WriteLine($"{rows,7} | {list,12} | {grows,12} | {array,12}");
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
namespace Open.Database.Extensions.Tests;

#nullable enable

/// <summary>
/// The rows of a reader of one <see cref="int"/> column, made once: a reader
/// over it allocates only itself, so the same column serves every call of an
/// allocation probe.
/// </summary>
/// <param name="Values">The value of each row.</param>
[ExcludeFromCodeCoverage]
internal sealed record Int32Column(int[] Values)
{
/// <summary>The columns every reader reports.</summary>
public static readonly ImmutableArray<ColumnDef> Columns = [new("Id", typeof(int))];

/// <summary>One empty slot per row, which the base reader steps through.</summary>
public object?[][] Slots { get; } = new object?[Values.Length][];

/// <summary>Makes the column of <paramref name="rows"/> rows: 0, 1, 2, ....</summary>
/// <param name="rows">The number of rows.</param>
/// <returns>The column.</returns>
public static Int32Column Of(int rows)
{
var values = new int[rows];
for (int i = 0; i < rows; i++) values[i] = i;
return new(values);
}
}

/// <summary>
/// An in-memory <see cref="System.Data.Common.DbDataReader"/> over one
/// <see cref="int"/> column whose typed getter does not allocate, as a
/// provider's does not. A <c>DataTableReader</c> boxes each value until the
/// JIT has optimized the read, so an allocation probe over one counts the
/// JIT's timing as well as the library's.
/// </summary>
/// <param name="column">The rows.</param>
[ExcludeFromCodeCoverage]
internal sealed class Int32ColumnReader(Int32Column column)
: TypedReader(Int32Column.Columns, column.Slots)
{
int _at = -1;

public override bool Read()
{
if (!base.Read()) return false;
++_at;
return true;
}

public override int GetInt32(int ordinal)
=> column.Values[_at];

public override bool IsDBNull(int ordinal)
=> false;

public override object GetValue(int ordinal)
=> column.Values[_at];

public override T GetFieldValue<T>(int ordinal)
=> (T)(object)column.Values[_at];
}