diff --git a/Benchmarks/Open.Database.Extensions.Benchmarks/CopyOutChecks.cs b/Benchmarks/Open.Database.Extensions.Benchmarks/CopyOutChecks.cs new file mode 100644 index 00000000..ffd9e674 --- /dev/null +++ b/Benchmarks/Open.Database.Extensions.Benchmarks/CopyOutChecks.cs @@ -0,0 +1,80 @@ +using System.Collections; +using System.Collections.Immutable; + +namespace Open.Database.Extensions.Benchmarks; + +// --verify-copyout: every variant of the copy-out benchmarks gives the same rows as the list that grows, +// for each row kind and a spread of counts that includes the edges of the scratch (8), the first chunk (16 after it) +// and a large result. A check, not a benchmark: it does not use BenchmarkDotNet and measures nothing. +static class CopyOutChecks +{ + static readonly int[] Counts = [0, 1, 5, 8, 9, 10, 16, 24, 25, 100, 1000, 8200, 100_000]; + + public static int Verify() + { + int failures = 0; + failures += Run(static () => new CopyOutInt(), static r => r); + failures += Run(static () => new CopyOutSmallStruct(), static r => r); + failures += Run(static () => new CopyOutClass(), static r => (r.Id, r.Name)); + Console.WriteLine(failures == 0 ? "copy-out variants: all equal" : $"copy-out variants: {failures} mismatch(es)"); + return failures == 0 ? 0 : 1; + } + + static int Run(Func create, Func key) + where TBenchmark : CopyOutCollectorBenchmarks + { + int failures = 0; + foreach (int rows in Counts) + { + TBenchmark bench = create(); + bench.Rows = rows; + bench.Setup(); + try + { + object[] expected = [.. Items(bench.Run(nameof(CopyOutCollectorBenchmarks<>.Sync_List_Grow))).Select(key)]; + if (expected.Length != rows) + { + Console.WriteLine($"{typeof(TBenchmark).Name} rows={rows}: the baseline gave {expected.Length} rows"); + failures++; + continue; + } + + foreach (string variant in CopyOutCollectorBenchmarks.Variants) + { + // Twice: the second call rents the parked chain and pooled arrays of the first. + for (int attempt = 0; attempt < 2; attempt++) + { + object? result = bench.Run(variant); + object[] actual = [.. Items(result).Select(key)]; + if (!expected.SequenceEqual(actual)) + { + Console.WriteLine($"{typeof(TBenchmark).Name} rows={rows} {variant}: rows differ ({actual.Length} against {expected.Length})"); + failures++; + break; + } + + // The exact-size claims of the copy-out terminals. + if ((variant.Contains("Chain") || variant == nameof(CopyOutCollectorBenchmarks<>.Sync_Scratch_ToList)) && result is List list && list.Capacity != rows) + { + Console.WriteLine($"{typeof(TBenchmark).Name} rows={rows} {variant}: capacity {list.Capacity}"); + failures++; + } + } + } + } + finally + { + bench.Cleanup(); + } + } + + return failures; + } + + static IEnumerable Items(object? result) => result switch + { + ImmutableArray array => array, + IEnumerable items => items, + _ => throw new InvalidOperationException("unexpected result " + result), + }; +} diff --git a/Benchmarks/Open.Database.Extensions.Benchmarks/CopyOutCollectorBenchmarks.cs b/Benchmarks/Open.Database.Extensions.Benchmarks/CopyOutCollectorBenchmarks.cs new file mode 100644 index 00000000..fe2e3d41 --- /dev/null +++ b/Benchmarks/Open.Database.Extensions.Benchmarks/CopyOutCollectorBenchmarks.cs @@ -0,0 +1,440 @@ +using System.Buffers; +using System.Collections.Immutable; +using System.Data; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Configs; +using Open.Database.Extensions.Core; + +namespace Open.Database.Extensions.Benchmarks; + +// The copy-out collectors (the terminals that hand the caller a list, an array or an immutable array) +// against the ways a caller would write the same thing by hand, over an in-memory DataTableReader +// (no database, no provider: the read itself costs the same in every variant). +// +// Chain_* the library's terminal as shipped: rows into pooled chunks, one copy out, the chunks +// cleared on the way back (value rows too: the copy-out rule when no pool is offered). +// RawChain_* the same chunk chain and copy-out as Chain_*, in the same raw read loop as List_Grow: no Map view, +// no abandon, none of the terminal's plumbing, so the difference to List_Grow is the collection strategy alone. +// Chain_* minus RawChain_* is what the terminal path itself costs. Needs the benchmark assembly to see +// Core's internals (InternalsVisibleTo in the Core project). +// List_Grow a List that grows, Add per row. +// List_ToArray that list, then ToArray(). +// Builder_ ImmutableArray.CreateBuilder() of unknown capacity, then ToImmutable(). +// Scratch_ a prototype that is NOT in the library: the first 8 rows go into a stack scratch buffer and +// only the ninth rents a pooled chunk, as System.Linq's internal builder does for ToArray +// (see the note on ScratchChain). Synchronous only: a ref struct cannot live across an await. +// +// Every variant reads through the same selector and returns its collection, which the harness consumes. +// The selector is a delegate field, so the library and the hand-written loops pay for it alike. +// Row kinds (one class each): int, a 16-byte struct, a class with a string. +// Filters: *CopyOutInt* *CopyOutSmallStruct* *CopyOutClass*, and within them *Sync_* or *Async_*. +// Rows come from ODX_COPYOUT_ROWS (default 0,1,5,10,100,1000,100000). +// Not run by the change that added it: the timed run needs a quiet machine. +// CopyOutChecks (--verify-copyout) checks, without BenchmarkDotNet, that every variant gives the same rows. +[MemoryDiagnoser] +[GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory, BenchmarkLogicalGroupRule.ByParams)] +public abstract class CopyOutCollectorBenchmarks +{ + [ParamsSource(nameof(RowsValues))] + public int Rows { get; set; } + + public static IEnumerable RowsValues() + { + string? value = Environment.GetEnvironmentVariable("ODX_COPYOUT_ROWS"); + return string.IsNullOrWhiteSpace(value) + ? [0, 1, 5, 10, 100, 1000, 100_000] + : value.Split(',').Select(static s => int.Parse(s.Trim())); + } + + DataTable _table = null!; + Func _read = null!; + + protected abstract Func Selector { get; } + + [GlobalSetup] + public void Setup() + { + var table = new DataTable(); + table.Columns.Add("Id", typeof(int)); + table.Columns.Add("Score", typeof(long)); + table.Columns.Add("Name", typeof(string)); + for (int i = 0; i < Rows; i++) table.Rows.Add(i, i * 2L, "name"); + _table = table; + _read = Selector; + } + + [GlobalCleanup] + public void Cleanup() => _table.Dispose(); + + // ---- synchronous ------------------------------------------------------ + + [Benchmark, BenchmarkCategory("Sync")] + public List Sync_Chain_ToList() + { + using DataTableReader reader = _table.CreateDataReader(); + return reader.Map(_read).ToList(); + } + + [Benchmark, BenchmarkCategory("Sync")] + public T[] Sync_Chain_ToArray() + { + using DataTableReader reader = _table.CreateDataReader(); + return reader.Map(_read).ToArray(); + } + + [Benchmark, BenchmarkCategory("Sync")] + public ImmutableArray Sync_Chain_ToImmutableArray() + { + using DataTableReader reader = _table.CreateDataReader(); + return reader.Map(_read).ToImmutableArray(); + } + + [Benchmark(Baseline = true), BenchmarkCategory("Sync")] + public List Sync_List_Grow() + { + using DataTableReader reader = _table.CreateDataReader(); + var list = new List(); + while (reader.Read()) list.Add(_read(reader)); + return list; + } + + [Benchmark, BenchmarkCategory("Sync")] + public T[] Sync_List_ToArray() + { + using DataTableReader reader = _table.CreateDataReader(); + var list = new List(); + while (reader.Read()) list.Add(_read(reader)); + return list.ToArray(); + } + + [Benchmark, BenchmarkCategory("Sync")] + public ImmutableArray Sync_Builder_ToImmutable() + { + using DataTableReader reader = _table.CreateDataReader(); + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); + while (reader.Read()) builder.Add(_read(reader)); + return builder.ToImmutable(); + } + + [Benchmark, BenchmarkCategory("Sync")] + public List Sync_Scratch_ToList() + { + using DataTableReader reader = _table.CreateDataReader(); + Scratch8 scratch = default; + // Not a using variable: that is read-only, and Add would run on a copy. + var chain = new ScratchChain(scratch); + try + { + while (reader.Read()) chain.Add(_read(reader)); + return chain.ToList(); + } + finally + { + chain.Dispose(); + } + } + + [Benchmark, BenchmarkCategory("Sync")] + public T[] Sync_Scratch_ToArray() + { + using DataTableReader reader = _table.CreateDataReader(); + Scratch8 scratch = default; + var chain = new ScratchChain(scratch); + try + { + while (reader.Read()) chain.Add(_read(reader)); + return chain.ToArray(); + } + finally + { + chain.Dispose(); + } + } + + [Benchmark, BenchmarkCategory("Sync")] + public List Sync_RawChain_ToList() + { + using DataTableReader reader = _table.CreateDataReader(); + using ChunkChain chain = ChunkChain.Rent(Views.Defaults.Config); + while (reader.Read()) chain.Add(_read(reader)); + return chain.ToList(); + } + + [Benchmark, BenchmarkCategory("Sync")] + public T[] Sync_RawChain_ToArray() + { + using DataTableReader reader = _table.CreateDataReader(); + using ChunkChain chain = ChunkChain.Rent(Views.Defaults.Config); + while (reader.Read()) chain.Add(_read(reader)); + return chain.ToArray(); + } + + [Benchmark, BenchmarkCategory("Sync")] + public ImmutableArray Sync_RawChain_ToImmutableArray() + { + using DataTableReader reader = _table.CreateDataReader(); + using ChunkChain chain = ChunkChain.Rent(Views.Defaults.Config); + while (reader.Read()) chain.Add(_read(reader)); + return default(ImmutableArrayBuild).Build(chain); + } + + // ---- asynchronous ----------------------------------------------------- + + [Benchmark, BenchmarkCategory("Async")] + public ValueTask> Async_Chain_ToList() + { + DataTableReader reader = _table.CreateDataReader(); + return Finish(reader, reader.Map(_read).ToListAsync()); + } + + [Benchmark, BenchmarkCategory("Async")] + public ValueTask Async_Chain_ToArray() + { + DataTableReader reader = _table.CreateDataReader(); + return Finish(reader, reader.Map(_read).ToArrayAsync()); + } + + [Benchmark, BenchmarkCategory("Async")] + public ValueTask> Async_Chain_ToImmutableArray() + { + DataTableReader reader = _table.CreateDataReader(); + return Finish(reader, reader.Map(_read).ToImmutableArrayAsync()); + } + + [Benchmark(Baseline = true), BenchmarkCategory("Async")] + public async ValueTask> Async_List_Grow() + { + using DataTableReader reader = _table.CreateDataReader(); + var list = new List(); + while (await reader.ReadAsync().ConfigureAwait(false)) list.Add(_read(reader)); + return list; + } + + [Benchmark, BenchmarkCategory("Async")] + public async ValueTask Async_List_ToArray() + { + using DataTableReader reader = _table.CreateDataReader(); + var list = new List(); + while (await reader.ReadAsync().ConfigureAwait(false)) list.Add(_read(reader)); + return list.ToArray(); + } + + [Benchmark, BenchmarkCategory("Async")] + public async ValueTask> Async_Builder_ToImmutable() + { + using DataTableReader reader = _table.CreateDataReader(); + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); + while (await reader.ReadAsync().ConfigureAwait(false)) builder.Add(_read(reader)); + return builder.ToImmutable(); + } + + [Benchmark, BenchmarkCategory("Async")] + public async ValueTask> Async_RawChain_ToList() + { + using DataTableReader reader = _table.CreateDataReader(); + using ChunkChain chain = ChunkChain.Rent(Views.Defaults.Config); + while (await reader.ReadAsync().ConfigureAwait(false)) chain.Add(_read(reader)); + return chain.ToList(); + } + + // The reader is the caller's: disposed when the terminal is done. + static async ValueTask Finish(DataTableReader reader, ValueTask terminal) + { + using (reader) return await terminal.ConfigureAwait(false); + } + + // The same calls, for the checks: every variant by name. + internal object? Run(string variant) => variant switch + { + nameof(Sync_Chain_ToList) => Sync_Chain_ToList(), + nameof(Sync_Chain_ToArray) => Sync_Chain_ToArray(), + nameof(Sync_Chain_ToImmutableArray) => Sync_Chain_ToImmutableArray(), + nameof(Sync_List_Grow) => Sync_List_Grow(), + nameof(Sync_List_ToArray) => Sync_List_ToArray(), + nameof(Sync_Builder_ToImmutable) => Sync_Builder_ToImmutable(), + nameof(Sync_RawChain_ToList) => Sync_RawChain_ToList(), + nameof(Sync_RawChain_ToArray) => Sync_RawChain_ToArray(), + nameof(Sync_RawChain_ToImmutableArray) => Sync_RawChain_ToImmutableArray(), + nameof(Sync_Scratch_ToList) => Sync_Scratch_ToList(), + nameof(Sync_Scratch_ToArray) => Sync_Scratch_ToArray(), + nameof(Async_RawChain_ToList) => Async_RawChain_ToList().AsTask().GetAwaiter().GetResult(), + nameof(Async_Chain_ToList) => Async_Chain_ToList().AsTask().GetAwaiter().GetResult(), + nameof(Async_Chain_ToArray) => Async_Chain_ToArray().AsTask().GetAwaiter().GetResult(), + nameof(Async_Chain_ToImmutableArray) => Async_Chain_ToImmutableArray().AsTask().GetAwaiter().GetResult(), + nameof(Async_List_Grow) => Async_List_Grow().AsTask().GetAwaiter().GetResult(), + nameof(Async_List_ToArray) => Async_List_ToArray().AsTask().GetAwaiter().GetResult(), + nameof(Async_Builder_ToImmutable) => Async_Builder_ToImmutable().AsTask().GetAwaiter().GetResult(), + _ => throw new ArgumentException(variant, nameof(variant)), + }; + + internal static readonly string[] Variants = + [ + nameof(Sync_Chain_ToList), nameof(Sync_Chain_ToArray), nameof(Sync_Chain_ToImmutableArray), + nameof(Sync_List_Grow), nameof(Sync_List_ToArray), nameof(Sync_Builder_ToImmutable), + nameof(Sync_RawChain_ToList), nameof(Sync_RawChain_ToArray), nameof(Sync_RawChain_ToImmutableArray), + nameof(Sync_Scratch_ToList), nameof(Sync_Scratch_ToArray), + nameof(Async_RawChain_ToList), + nameof(Async_Chain_ToList), nameof(Async_Chain_ToArray), nameof(Async_Chain_ToImmutableArray), + nameof(Async_List_Grow), nameof(Async_List_ToArray), nameof(Async_Builder_ToImmutable), + ]; +} + +/// A row with no references: 16 bytes. +public readonly record struct CopyOutStruct(int Id, long Score); + +/// A row that is a class with a string. +public sealed class CopyOutClassRow(int id, string name) +{ + public int Id { get; } = id; + + public string Name { get; } = name; +} + +[MemoryDiagnoser] +public class CopyOutInt : CopyOutCollectorBenchmarks +{ + protected override Func Selector { get; } = static r => r.GetInt32(0); +} + +[MemoryDiagnoser] +public class CopyOutSmallStruct : CopyOutCollectorBenchmarks +{ + protected override Func Selector { get; } = static r => new(r.GetInt32(0), r.GetInt64(1)); +} + +[MemoryDiagnoser] +public class CopyOutClass : CopyOutCollectorBenchmarks +{ + protected override Func Selector { get; } = static r => new(r.GetInt32(0), r.GetString(2)); +} + +/// Eight inline slots, for the caller's stack. +[InlineArray(8)] +public struct Scratch8 +{ + T _element0; +} + +/// Up to 27 segments, held inline, so the builder allocates no array of arrays. +[InlineArray(27)] +public struct Segments +{ + T[] _element0; +} + +// A prototype for the question "would a small stack scratch in front of the chain win at small counts?". +// Modelled on what System.Linq does for Enumerable.ToArray of a source of unknown length: its internal +// SegmentedArrayBuilder (dotnet/runtime, src/libraries/System.Linq/src/System/Linq/SegmentedArrayBuilder.cs, +// tags v10.0.15 and v11.0.0, identical) keeps the first 8 items in a stack buffer the caller passes in, +// then rents segments of at least 16 from ArrayPool.Shared, each at least twice the last, held in 27 inline slots. +// There the segments of a type with references are cleared before they are returned, and others are not. +// This prototype follows the library's rule for a copy-out instead: the used part of every segment is cleared. +// Its chunk schedule is the library's own default (16, doubling to 8,192). It holds at most 27 segments, about 155,000 rows (more throws), as the benchmark rows stop at 100,000. Not part of the library. +public ref struct ScratchChain : IDisposable +{ + const int FirstRows = 16; + const int MaxRows = 8192; + const int MaxSegments = 27; + + readonly Span _scratch; + Segments _segments; + int _segmentCount; + Span _current; + int _index; + int _finished; + + public ScratchChain(Span scratch) + { + _scratch = scratch; + _current = scratch; + } + + public readonly int Count => _finished + _index; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Add(T item) + { + int index = _index; + Span current = _current; + if ((uint)index < (uint)current.Length) + { + current[index] = item; + _index = index + 1; + return; + } + + AddSlow(item); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + void AddSlow(T item) + { + if (_segmentCount == MaxSegments) + throw new NotSupportedException("The prototype holds at most " + MaxSegments + " segments (about 155,000 rows)."); + + int last = _segmentCount == 0 ? _scratch.Length : _segments[_segmentCount - 1].Length; + int size = _segmentCount == 0 ? FirstRows : Math.Min(last * 2, MaxRows); + T[] next = ArrayPool.Shared.Rent(size); + _finished += _current.Length; + _segments[_segmentCount++] = next; + _current = next; + next[0] = item; + _index = 1; + } + + readonly void CopyTo(Span destination) + { + if (_segmentCount == 0) + { + _scratch[.._index].CopyTo(destination); + return; + } + + _scratch.CopyTo(destination); + int offset = _scratch.Length; + for (int i = 0; i < _segmentCount - 1; i++) + { + T[] segment = _segments[i]; + segment.CopyTo(destination[offset..]); + offset += segment.Length; + } + + _segments[_segmentCount - 1].AsSpan(0, _index).CopyTo(destination[offset..]); + } + + public readonly List ToList() + { + int count = Count; + var list = new List(count); + CollectionsMarshal.SetCount(list, count); + CopyTo(CollectionsMarshal.AsSpan(list)); + return list; + } + + public readonly T[] ToArray() + { + if (Count == 0) return []; + + var array = new T[Count]; + CopyTo(array); + return array; + } + + public void Dispose() + { + for (int i = 0; i < _segmentCount; i++) + { + T[] segment = _segments[i]; + int used = i == _segmentCount - 1 ? _index : segment.Length; + segment.AsSpan(0, used).Clear(); + ArrayPool.Shared.Return(segment); + } + + _segmentCount = 0; + _current = default; + _index = 0; + _finished = 0; + } +} diff --git a/Benchmarks/Open.Database.Extensions.Benchmarks/Program.cs b/Benchmarks/Open.Database.Extensions.Benchmarks/Program.cs index 382bba7a..4f9693f1 100644 --- a/Benchmarks/Open.Database.Extensions.Benchmarks/Program.cs +++ b/Benchmarks/Open.Database.Extensions.Benchmarks/Program.cs @@ -17,8 +17,9 @@ // -- --selftest-s4 the large-value probe's cell runner, result line and checksum, on SQLite (--s4, --s4-setup, --s4-teardown: see S4Probe.cs) // -- --verify-rp --scratch [--sqlite-dir ] equal final objects from every real-provider variant (LocalDB and a SQLite file), see RealProviderBenchmarks.cs // -- --verify-gate every gate case's rows and read modes (ODX_GATE_SOURCES, ODX_RP_SCRATCH), see GateBenchmarks.cs +// -- --verify-copyout every variant of the copy-out collector benchmarks gives the same rows (see CopyOutCollectorBenchmarks.cs) // The checks say which runtime and target framework they ran on (the build is multi-targeted). -if (args.Any(static a => a is "--verify" or "--selftest-open-time" or "--selftest-alloc" or "--selftest-pace" or "--selftest-refill" or "--selftest-in6" or "--verify-rp" or "--verify-gate" or "--calibrate-spin" or "--in6") || S4Probe.Handles(args)) +if (args.Any(static a => a is "--verify" or "--verify-copyout" or "--selftest-open-time" or "--selftest-alloc" or "--selftest-pace" or "--selftest-refill" or "--selftest-in6" or "--verify-rp" or "--verify-gate" or "--calibrate-spin" or "--in6") || S4Probe.Handles(args)) { Console.WriteLine("runtime: " + System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription + ", built for: " + System.Reflection.Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(System.Runtime.Versioning.TargetFrameworkAttribute), false) @@ -43,6 +44,12 @@ return; } +if (args.Contains("--verify-copyout")) +{ + Environment.ExitCode = CopyOutChecks.Verify(); + return; +} + if (args.Contains("--selftest-open-time")) { Environment.ExitCode = SyntheticChecks.SelfTestOpenTime(); diff --git a/Source/Core/Open.Database.Extensions.Core.csproj b/Source/Core/Open.Database.Extensions.Core.csproj index 400fff8a..1e01a286 100644 --- a/Source/Core/Open.Database.Extensions.Core.csproj +++ b/Source/Core/Open.Database.Extensions.Core.csproj @@ -30,7 +30,8 @@ + target the conversion of the tuple convenience overloads into a RowMap. + The Benchmarks assembly measures the internal chunk chain beside the hand-written collectors (CopyOutCollectorBenchmarks). --> @@ -38,6 +39,7 @@ +