diff --git a/README.md b/README.md index 6d8c1320..44652a4d 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,9 @@ Open.Database.Extensions handles the ADO.NET code around your own SQL with one fluent command: create the connection, add the parameters, run it, map the rows, dispose everything, the way ADO.NET best practice says. It works with any ADO.NET provider and the ADO.NET types you already use, and holds a connection open only while a query needs it. -**[Documentation](https://open-net-libraries.github.io/Open.Database.Extensions/)** · [Getting started](https://open-net-libraries.github.io/Open.Database.Extensions/articles/getting-started.html) · [API reference](https://open-net-libraries.github.io/Open.Database.Extensions/api/index.html) · [Benchmarks](https://github.com/Open-NET-Libraries/Open.Database.Extensions/blob/master/Benchmarks/RESULTS.md) +**[Documentation](https://open-net-libraries.github.io/Open.Database.Extensions/)** · [Getting started](https://open-net-libraries.github.io/Open.Database.Extensions/articles/getting-started.html) · [API reference](https://open-net-libraries.github.io/Open.Database.Extensions/api/index.html) · [Benchmarks](https://github.com/Open-NET-Libraries/Open.Database.Extensions/blob/master/Benchmarks/RESULTS.md) · [Presentation](https://open-net-libraries.github.io/Open.Database.Extensions/presentation/) + +[![The features of ODX v11, one slide at a time.](https://raw.githubusercontent.com/Open-NET-Libraries/Open.Database.Extensions/master/docsite/images/feature-slideshow.svg)](https://open-net-libraries.github.io/Open.Database.Extensions/presentation/index.html) ## Before and after diff --git a/docsite/docfx.json b/docsite/docfx.json index f6adaf3a..615293b3 100644 --- a/docsite/docfx.json +++ b/docsite/docfx.json @@ -37,7 +37,7 @@ ], "resource": [ { - "files": [ "images/**", "perf-data/**", "benchmarks/**" ] + "files": [ "images/**", "perf-data/**", "benchmarks/**", "presentation/**" ] } ], "overwrite": [ diff --git a/docsite/images/feature-slideshow.svg b/docsite/images/feature-slideshow.svg new file mode 100644 index 00000000..f10193b5 --- /dev/null +++ b/docsite/images/feature-slideshow.svg @@ -0,0 +1,73 @@ + + ODX v11 features + 1. You write the SQL. 22 lines → 5. Post[] posts = await connectionFactory .Command("select * from posts where author = @author order by id") .AddParam(author) // name and type inferred from the variable .Map<Post>() .ToArrayAsync(cancellationToken); Plain ADO.NET against ODX, counted from compiled samples, blank lines excluded. 2. Generated model readers. As fast as hand-written ADO.NET. The build writes the model reader you would write by hand. You write .Map<Post>(). The build generates (a sketch): Post Row(IDataRecord r) => new Post(r.GetInt32(0), r.GetInt32(1), r.GetString(2)); Same time and same memory as a reader written by hand, within the margin of error. 3. Define once, bind where it runs. Declare it once. Immutable, no connection, safe in a static field. static readonly MappedDbQuery<Post> ByAuthor = DbQuery.Text(ListSql).Map<Post>(); Bind the source and values at the call: Using(connectionFactory).AddParam(author). 4. Correct by default. Open late, close early. A connection you gave it is never disposed. null into a non-nullable member throws ValueMappingException. A failure in a later result set is still thrown. A factory's connection is disposed; a pool's is given back. 5. Read it your way. Buffered by default. Read every row, release the connection, then do your work. .ToArrayAsync(ct) all rows, connection released. .Stream(stallTimeout, ct) rows as they arrive, with a stall timeout. .CancelOnEarlyStop() first row of 3 million: 202 ms → 0.4 ms. Stop-early is opt-in, measured on SQL Server LocalDB. No help for a TOP 1 or key lookup. 6. Get started. dotnet add package Open.Database.Extensions.Core. MIT. Any ADO.NET provider. .NET 10 and 11, .NET Standard 2.0 and 2.1. SQL Server helpers: Open.Database.Extensions.MSSqlClient. + + + +1 / 6 · You write the SQL22 lines → 5ADO.NET22ODX5Post[] posts = await connectionFactory .Command("select * from posts where author = @author order by id") .AddParam(author) // name and type inferred from the variable .Map<Post>() .ToArrayAsync(cancellationToken);Plain ADO.NET against ODX, counted from compiled samples, blank lines excluded. +2 / 6 · Generated model readersAs fast as hand-written ADO.NET.The build writes the model reader you would write by hand.You writeThe build generates (a sketch).Map<Post>()Post Row(IDataRecord r) => new Post( r.GetInt32(0), r.GetInt32(1), r.GetString(2));Same time and same memory as a reader written by hand, within the margin of error. +3 / 6 · Define once, bind where it runsDeclare it once.Immutable, no connection, safe in a static field.static readonly MappedDbQuery<Post> ByAuthor = DbQuery.Text(ListSql).Map<Post>();Bind the source and values at the call: Using(connectionFactory).AddParam(author). +4 / 6 · Correct by defaultOpen late, close early.A connection you gave it is never disposed.null into a non-nullable member throws ValueMappingException.A failure in a later result set is still thrown.A factory's connection is disposed; a pool's is given back. +5 / 6 · Read it your wayBuffered by default.Read every row, release the connection, then do your work..ToArrayAsync(ct)all rows, connection released.Stream(stallTimeout, ct)rows as they arrive, with a stall timeout.CancelOnEarlyStop()first row of 3 million: 202 ms → 0.4 msStop-early is opt-in, measured on SQL Server LocalDB. No help for a TOP 1 or key lookup. +6 / 6 · Get starteddotnet add packageOpen.Database.Extensions.CoreMIT. Any ADO.NET provider..NET 10 and 11, .NET Standard 2.0 and 2.1.SQL Server helpers: Open.Database.Extensions.MSSqlClient. +ODX v11 + + + + + + + diff --git a/docsite/index.md b/docsite/index.md index ec3fa8ea..c7d8d528 100644 --- a/docsite/index.md +++ b/docsite/index.md @@ -6,6 +6,10 @@ title: Open.Database.Extensions (ODX) Extensions on the standard ADO.NET types that make everyday database work short to write and robust by default. Version 11 is a release candidate. +![The features of ODX v11, one slide at a time.](images/feature-slideshow.svg) + +[Presentation](presentation/index.html): a slide deck on why to use ODX, with speaker notes. + [!code-csharp[](samples/BeforeAfter.cs#ode_list_factory)] Here `author` is an `int` variable: the parameter name `author` comes from the argument. diff --git a/docsite/presentation/index.html b/docsite/presentation/index.html new file mode 100644 index 00000000..dbb736ad --- /dev/null +++ b/docsite/presentation/index.html @@ -0,0 +1,2501 @@ + + + + + +ODX v11: a presentation for developers + + + + + +
+
+ + +
+
Version 11.0
+

Open.Database.Extensions
(ODX) v11

+

You write the SQL.
ODX writes the other twenty lines.

+

Extensions on the ADO.NET types you already use. Any provider. MIT.

+

open-net-libraries.github.io/Open.Database.Extensions

+ +
+ + +
+

The problem

+

One author's posts, with plain ADO.NET: 22 lines.

+
+
+ +
var posts = new List<Post>();
+await using var connection = new SqliteConnection(connectionString);
+await connection.OpenAsync(cancellationToken);
+await using var command = connection.CreateCommand();
+command.CommandText =
+    "select id, author, title, body from posts "
+    + "where author = @author order by id";
+var parameter = command.CreateParameter();
+parameter.ParameterName = "@author";
+parameter.Value = author;
+command.Parameters.Add(parameter);
+await using var reader = await command.ExecuteReaderAsync(cancellationToken);
+while (await reader.ReadAsync(cancellationToken))
+{
+    posts.Add(new Post
+    {
+        Id = reader.GetInt32(0),
+        Author = reader.GetInt32(1),
+        Title = reader.GetString(2),
+        Body = reader.IsDBNull(3) ? null : reader.GetString(3),
+    });
+}
+
← the part you meant to write
+
+
+ Connection + Command + Parameter + Read loop + Column copying + Disposal +
+
+ +
+ + +
+

ODX in one call

+

You keep your SQL. ODX does the rest.

+
int author = 42;
+
+Post[] posts = await connectionFactory
+    .Command("select * from posts where author = @author order by id")
+    .AddParam(author) // name and type inferred from the variable
+    .Map<Post>()
+    .ToArrayAsync(cancellationToken);
+
+
+

Not written by you

+
+ ✓ Connection + ✓ Command + ✓ Parameter + ✓ Read loop + ✓ Column copying + ✓ Disposal +
+
+
+

Lines you write

+
ADO.NET
22
+
ODX
5
+
+
+

connectionFactory is created once per application.

+ +
+ + +
+

Setup once, code per call

+

An ORM looks like less code because the setup is written somewhere else.

+
+
+

ODX: not an ORM. Define once, you write the SQL

+
static readonly MappedDbQuery<Post> AllPosts
+    = DbQuery.Text(AllPostsSql).Map<Post>();
+
+// per call
+=> AllPosts.Using(connectionFactory)
+    .ToListAsync(cancellationToken);
+
+
+

EF Core: an ORM with change tracking and SaveChanges.
A context first, then LINQ

+
// per call
+=> db.Posts.OrderBy(static p => p.Id)
+    .ToListAsync(ct);
+
+
+
+

Lines you write for task 1, rows to a list: once, and per call

+
onceper call
+ +
ODX
7 per call, 1–3 once
+
EF Core
6 per call, 5 once+ configuration, registration: not counted
+
Dapper
9 per call, no setup
+
ADO.NET
22 per call, no setup
+
+

Dapper and ADO.NET create the connection in every call.

+ +
+ + +
+

Hand-written is the ceiling

+

A reader written by hand has nothing to work out at run time.

+
+
+
Once per result set
match column names, check the layout→fixed ordinals
+
Per row
work out the shape→plain loop
+
Per cell
look up, box, convert→GetInt32(0)
+

It is also code you write and keep in step with every query by hand.

+
+
+ +
[rc.16]µs
+

Hand-written selector.
Connection held open, 20 columns,
1,000 rows, synthetic reader.

+ +
+
+ +
+ + +
+

ODX generates that code for you

+

So plain .Map<T>() reaches the ceiling. Nothing to write.

+ +The source generator writes a reader from your model and hands it to the same Map(selector) path as a hand-written selector. + + Post (your model) + int Id + string Title + string? Body + + + + + build time + generator + + + Generated reader + Id = r.GetInt32(0), + Title = r.GetString(1), + sketch, not the real output + + + + Hand-written selector + you write it + + + + + + + + The same path + Map(selector) + + + + + rows + + + + Generic method: runtime map, + compiled once per shape, cached + + +
Opt out: <OdxGenerateMaps>false</OdxGenerateMaps>C# 12 or later
+ +
+ + +
+

Against Dapper and Dapper.AOT

+

Same query, same rows. 20 columns, 1,000 rows, synthetic reader (no database).

+
+
+

Connection held open (shorter is better)

+
+ +
Hand-written selector[rc.16]
+ +
ODX Map<T>()[rc.16]
+ +
Dapper.AOT[rc.16]
+ +
Dapper Query<T>[rc.16]
+
+

Memory allocated

+
+ +
ODX, selector, AOT[rc.16]
+ +
Dapper Query<T>[rc.16]
+
+
+
+
+ +
[rc.16]×less connection time
than Dapper
+
[rc.16]×less memory
than Dapper
+
+
+

Real database, 10,000 rows of 20 columns.
ODX = 1.00, shorter is better.

+
+ +

SQL Server LocalDB: time

+
ODX1.00
+
Dapper+[rc.16]
+

SQLite file: time

+
ODX1.00
+
Dapper+[rc.16]
+ +

SQL Server: memory

+
ODX1.00
+
Dapper+[rc.16]
+

SQLite: memory

+
ODX1.00
+
Dapper+[rc.16]
+
+
+
+
+ +
+ + +
+

Define once, bind where it runs

+

A query is a value: immutable, no connection, safe in a static field.

+
// Recommended.
+static readonly MappedDbQuery<Post> ByAuthor
+    = DbQuery.Text(ListSql).Map<Post>();
+
+public ValueTask<List<Post>> ByAuthorAsync(
+    int author,
+    CancellationToken cancellationToken)
+    => ByAuthor.Using(connectionFactory)
+        .AddParam(author)
+        .ToListAsync(cancellationToken);
+

One-row call at 20 columns, µs, runtime map. Shorter is better.

+
Map cached, reused
+
0.28 about 3,100 times
+
New RowMap<T> at the call site
+
870
+

Building the map: 190 to 870 µs for 1 to 20 columns.
With the generator, at build time, except in a generic method.

+ +
+ + +
+

Parameters from arguments

+

The name comes from the variable. For a stored procedure it is matched to the real one.

+
+
+
Post[] posts = await connectionFactory
+    .Command("select * from posts where author = @Author order by id")
+    .AddParam(search.Author) // name and type inferred from the member
+    .Map<Post>()
+    .ToArrayAsync(cancellationToken);
+

A stored procedure (SQL Server)

+
=> db.StoredProcedure("[dbo].[SearchPosts]")
+    .AddParam(author)
+    .AddParam(titleContains)
+    .Map<Post>()
+    .ToListAsync(ct);
+
+
+ + your argument + + titleContains + + procedure declares + @author + + @title_contains + 1exactly + 2ignoring case + + 3ignoring case + and underscores + + then: a common prefix dropped,then a chain's shorter endings + ✗ + ✗ + ✓ + + + + a literal needs a name: + AddParam("author", 42) + no match: throws and says what it declares + + +

Names remembered five minutes per factory.

+
+
+ +
+ + +
+

Correct by default

+

Errors are loud. Declarations are hard rules.

+
+
+
public record Post
+{
+    [Column("id", Order = 0)]
+    public required int Id { get; init; }
+
+    [Column("title", Order = 1)]
+    public string Title { get; init; } = "";
+
+    // Not mapped: no column is ever
+    // read into it.
+    [NotMapped]
+    public string Slug { get; init; } = "unset";
+}
+
var posts = await command.SingleResult()
+    .Map<Post>()
+    .ToListAsync(cancellationToken);
+
+
+ +null into a non-nullable member +Postrow 0 + +int Id +int Id✓ +1row 1 + +int Id +int Id✓ +2row 2 + +int Id +int Id✗ +null +ValueMappingException +Post, row 2 +int? gives null +Later result sets: read through +result set 1result set 2 +an error + +ODX keeps reading +✗ +set 1: read +thrown, not lost +First set only +.SingleResult() +result set 1result set 2 +not read + +stop +stops after set 1 +set 2: not read +Declarations are hard rules +[Column("id", Order = 0)]Idread as declared✓ +[Column("title", Order = 1)]Titleread as declared✓ +[NotMapped]Slugno column is readkeeps "unset" +[Column("title", Order = 1)]Titledeclared, but missingthrows ValueMappingException + +
+
+ +
+ + +
+

Connection ownership

+

Open if needed. Close only what you opened.

+
+
+
// A closed connection is opened for the call
+// and closed again afterwards.
+await connection.CloseAsync();
+await connection.Command("select 1")
+    .ExecuteScalarAsync(cancellationToken);
+
+// A connection that was already open stays open.
+await connection.OpenAsync(cancellationToken);
+await connection.Command("select 1")
+    .ExecuteScalarAsync(cancellationToken);
+
+
+ +1  From a factory +factory +pool + +closed +open +ODX opens +ODX closes +the call + + +disposed +a pool's connection is given back +2  Your connection, closed +you +still yours +closed +open +ODX opens +ODX closes +the call +closed again +never disposed +3  Your connection, open +you +still yours +open +the call +stays open +4  When the query fails +From a factory +✗ fails + + +disposedback to the pool +Your connection,closed +✗ fails + + +closed againnever disposed +Your connection,open +✗ fails + + +stays openstill yours +A SQL error, a timeout or a cancel:the connection is put back, then the exception reaches you. + +
+
+ +
+ + +
+

Why hold time matters

+

A fixed number of connections. The same requests. Only the hold time differs.

+ Illustrative model: not measured + +
+ + +
+

Requests wait for a free connection. A connection pool has a maximum size, and a database a limited number of workers. Queueing at scale was not measured, and neither was the gain from releasing a thread.

+ +
+ + +
+

One set of rows

+

The usual stack copies rows into DTOs. Here they are read once.

+ + Copies of copies, or one copy + Two lanes read left to right, the classic stack on top and ODX below, with the database, the serializer and the JSON in the same places. Classic lane: the database, then a repository that reads the rows into entities and a list, the first set of row objects; then a service that copies the entities into DTOs and another list, the second set; then the serializer and the JSON. A caption says there are two sets of row objects and two lists, and the garbage collector takes them all after the response. ODX lane: the database, then the command factory, whose rows are read once into Post objects in pooled arrays, the only set; then the serializer and the JSON. Below the pooled arrays is the array pool: the arrays are rented from it for the read and go back to it after the response. A caption says there is one set of row objects and the arrays are reused by later requests. The figure shows no measurements. + + + + + + + + + + + + Copies of copies, or one copy + + + Classic: repository, service, DTOs + + + database + + + + + + repository + entities + List<PostEntity> + + + + + + + + + service + DTOs, copied + List<PostDto> + + + + + + + + + serializer + + + + + + JSON + + + + 1st set of objects + + 2nd set of objects + + Two sets of row objects and two lists. The garbage collector takes them all after the response. + + + ODX: command factory + + + database + + + + + + command factory + Post rows, read once + into pooled arrays + + + + + the only set + + + + + + serializer + + + + + + JSON + + + + + rented for the read + + back after the response + + + array pool + + + One set of row objects. The arrays are reused by later requests. + + +
+ + +
+

Buffered results, no service layer

+

The controller calls the query and returns the pooled rows.

+
+
+
// Command factory: each query defined once.
+static readonly MappedDbQuery<Post> ByAuthorQuery
+    = DbQuery.Text(ListSql).Map<Post>();
+
+public MappedQuery<Post> ByAuthor(int author)
+    => ByAuthorQuery.Using(connectionFactory)
+        .AddParam(author)
+        .UsePool(pool, clearOnReturn: true);
+
+[HttpGet("by-author/{author}")]
+public Task<PooledArray<Post>> ByAuthorAsync(
+    int author)
+    => commands.ByAuthor(author)
+        .ToPooledBuffer(HttpContext.RequestAborted)
+        // The framework disposes it after the response,
+        // and awaits the rows, then writes them.
+        .RegisterForDispose(Response);
+
+
+
    +
  • ToArrayAsync: fastest to a finished array.
    One exact copy.
  • +
  • ToPooledBuffer: no final copy.
    Readable while it fills.
    Arrays back to the pool on dispose.
  • +
+ +
+
+ +
+ +
+

The journey of a result

+

Query, controller, response, dispose: where the rows are copied.

+ +The journey of a result +Two flows. ToArrayAsync: rows are read into pooled chunks, the connection is released at the last row, the rows are copied once into a new exactly sized array, the chunks go back to the pool, the controller serializes the array and the array is left to the garbage collector. ToPooledBuffer: all rows are read into pooled chunks in a background task while the call returns at once, the connection is released at the last row, the controller serializes straight from the chunks with no copy and no extra array, the buffer is disposed after the response and the chunks go back to the pool to be reused. A strip under each flow shows the two clocks, the connection held and the total time. No measurements are shown. + + + + + + + +ToArrayAsyncthe read is over before the response startsDBcontrollerserializeJSONcopyto the GCconnection heldtotal time, until you are done with the rowsdatabaseRead into pooled chunksconnection released at the last rowthen the chunks go back to the poolCopy once into a new arrayexact size; class rows: referencesEnd: the array is left to the GCRespond: the controllerserializes the array + +ToPooledBufferhere: Items, after the last rowDBcontrollerserializeJSONdispose: back to the poolconnection heldtotal time, until you are done with the rowsdatabaseRead: all rows into pooledchunks in a background task;the call returns at once;connection released at last rowHand over: no copy and no extraarray, the controller readsthe chunks themselvesRespond: serializes the chunksEnd: the buffer is disposedafter the response; chunks goback to the pool, reused next +no copyno extra arrayarrays reused + +

Full request, JSON response|total time: ToPooledBuffer [rc.16] against ToArrayAsync [rc.16]|memory: [rc.16] against [rc.16]

+ +
+ +
+

While it fills

+

Read each chunk as it is published. Dispose sends the chunks back.

+ +While it fills +Two ToPooledBuffer flows. Top: the buffer is enumerated while it fills. The rows are read into pooled chunks in a background task; each whole chunk is handed to the controller as soon as it is published, so the controller serializes the first chunks while the read goes on; the connection is released at the last row; dispose sends the chunks back to the pool. Bottom: the Items property waits for all rows before the controller starts. No measurements are shown. + + + + + + +await foreach (var post in buffer)enumerated: each chunkDBcontrollerserializeJSONdispose: back to the poolconnection heldtotal time, until you are done with the rowsdatabaseRead: all rows into pooledchunks in the background;connection released at last rowEnumerate: the controller takeseach chunk as it is published,never a half-filled oneRespond: serializes each chunkEnd: the buffer is disposed;chunks go back to the poolawait buffer.ItemsItems: waits for all rowsDBcontrollerserializeJSONdispose: back to the poolconnection heldtotal time, until you are done with the rowsdatabaseRead: all rows into pooledchunks in a background task;the call returns at once;connection released at last rowHand over: no copy and no extraarray, the controller readsthe chunks themselvesRespond: serializes the chunksEnd: the buffer is disposedafter the response; chunks goback to the pool, reused nextwhole chunks, as each is published + +

Full request, JSON response|total time: enumerated [rc.16] against Items [rc.16]

+ +
+ + +
+

Streaming, safely

+

Stream(stallTimeout) and StreamBuffered: use them to stop early.
To read all rows, use ToArrayAsync.

+
+
+
// Only to stop early: Stream holds the connection
+// open while each row is read.
+// The timeout is the longest you may go
+// without pulling the next row.
+// To read all the rows, use ToArrayAsync,
+// the buffered way.
+await foreach (Post post in connection
+    .Command("select * from posts order by id")
+    .Map<Post>()
+    .Stream(TimeSpan.FromSeconds(30), cancellationToken))
+{
+    stoppedAt = post.Id;
+    if (post.Title == "Post 3")
+    {
+        break;
+    }
+}
+
+
+

Reader held open, 10,000 rows, ms.
The consumer gets slower:

+
ToPooledBufferStreamno buffer
+
40 ns per row
6.19
6.39
+
1 µs per row
6.26
16.01
+
20 µs wait
per 100 rows
6.17
8.01
+

Synthetic provider, one run: not a real database.

+

StreamBuffered: reads ahead, up to 1,024 rows.

+ + rows pulled + + + + + your loop is busy + + + stallTimeout + read stopped, command canceled, connection closed + next pull: TimeoutException + +
+
+ +
+ + +
+

Stop early

+

CancelOnEarlyStop(): opt in, when the query returns far more rows than you need.

+
+
+
Post? newest = await DbQuery.Procedure("GetPostsNewestFirst")
+    .Using(connectionFactory)
+    .Map<Post>()
+    .CancelOnEarlyStop()
+    .FirstOrDefaultAsync(cancellationToken);
+

FirstOrDefaultAsync over 3 million rows,
SQL Server LocalDB, ms. Shorter is better.
The 0.4 bar is drawn at a minimum width.

+
Without it
202
+
SingleResult() alone
202
+
CancelOnEarlyStop()
0.4
+ Illustrative: not to scale + + + + + + Without it + every row is sent + + CancelOnEarlyStop() + the rest is discarded + + + + cancel + +
+
+

When it does not help

+
    +
  • A TOP 1 or key lookup:
    about 80 µs either way.
  • +
+

Do not use it with

+
    +
  • A batch whose later statements matter: they may or may not run, and their errors are not reported.
  • +
  • BEGIN TRAN in the SQL or XACT_ABORT: not detected by ODX, so do not combine them with it.
  • +
  • A transaction, an output parameter or a TransactionScope: refused with InvalidOperationException.
  • +
+
+
+ +
+ + +
+

Greedy or polite

+

Who holds the connection longer, when the thread pool is busy.

+ Illustrative: not to scale + + + + + + + + Greedy + Read() + the default + Polite + ReadAsync() + AsyncReads() + + + connection open + + + + + + + + rows + + + + + + + network wait: keeps its thread + + + + closed + + + + connection open + + + + + + + + + + + + + + + + + + rows + + thread given back + in line fora free thread + + + + closed + + + + + + + + + connection held open longer + + + + + thread pool: busy + + + + + + busybusybusybusy + + waiting + + + + + + + + + + + + time + + +
+ + +
+

Async done right

+

Row reads are synchronous by default.
AsyncReads() opts in to full async.

+
+
+

Default

+
List<Post> posts = await connection
+    .Command("select * from posts order by id")
+    // No AsyncReads(): the default.
+    .Map<Post>()
+    .ToListAsync(cancellationToken);
+

Opt in: full async. Every await per row adds to the time the connection is held

+
List<Post> posts = await connection
+    .Command("select * from posts order by id")
+    .AsyncReads()
+    .Map<Post>()
+    .ToListAsync(cancellationToken);
+
+
+

Connection held open, µs. One scale: shorter is better.

+
Default (ODX)AsyncReads()
+
Rows ready
+
77.4
+
80.0
+
Busy thread pool
+
95.6
+
99.3
+
Network waits (refills)
+
262.4
+
285.8
+
Refills plus busy pool
+
279.8
+
2,227
+ AsyncReads(): 8.0 times as long
+

Synthetic reader, 20 columns, 1,000 rows. Refill: a 20 µs wait every 100 rows. Busy pool: 8 queued work items. One run per case.

+
+

Real SQL Server over a simulated 5 ms, 100 Mbit link

+
+
+

Time: the same

+
Default
538.3 ms
+
AsyncReads()
538.2 ms
+

the link sets the time

+
+
+

Memory: +73% with AsyncReads()

+
Default
9,713 KB
+
AsyncReads()
16,812 KB
+

per operation, Map(Func)

+
+
+
+
+
+ +
+ + +
+

Honest benchmarks

+

Every page says how it was measured and where ODX is not faster.

+
+
HowBenchmarkDotNet 0.15.8, Release, one desktop PC (AMD Ryzen 9 7900, Windows 10); .NET 11.0.0 for the library and width runs, .NET 10.0.15 for the pool store tests.
+
WhatSynthetic reader for the library's own cost. SQL Server LocalDB and SQLite for what survives.
+
CheckedAll variants return the same rows: a --verify check fails if they differ.
+
+

Where it is not faster

+ +

Gaps of a few percent are noise; several error margins are as large as the differences.
Full pages: open-net-libraries.github.io/Open.Database.Extensions/articles/performance.html

+ +
+ + +
+

Get started

+

Version 11.0 on NuGet.

+
dotnet add package Open.Database.Extensions.Core
+ + + + + + +
PackageUse it for
Open.Database.Extensions.CoreEverything, provider-agnostic
Open.Database.Extensions.MSSqlClientSqlConnectionFactory, SQL Server
Open.Database.Extensions.ChannelReading into channels
Open.Database.Extensions.DataflowReading into dataflow blocks
+

Core targets netstandard2.0, netstandard2.1, net10.0, net11.0. MSSqlClient: net472, net10.0, net11.0. MIT license.

+

Moving from 10.x: Coming from earlier versions

+

open-net-libraries.github.io/Open.Database.Extensions

+ +
+ + +
+

Go deeper

+

Pick a topic.

+ + +
+ + +
+

How little code

+

Four tasks, all async. Lines per method, signature to closing brace.
EF Core's context is not counted (see Setup once, code per call).

+ ← Go deeper +
ODXDapperEF CoreADO.NET
+
1. Rows to a list
+
7
+
9
+
6
+
22
+
2. Filter in SQL, project in C#,
async stream
+
10
+
14
+
8
+
22
+
3. One author's rows in memory,
then LINQ
+
15
+
15
+
13
+
26
+
4. A stored procedure,
two parameters
+
11
+
14
+
12
+
29
+

Per-call methods only. Blank lines and comments not counted. The ODX connection factory and the EF Core context are set up once:
see Setup once, code per call. Every snippet is compiled.

+ +
+ + +
+

Cost per column

+

Nanoseconds for one more cell. Synthetic reader, 1,000 rows, 1 to 20 columns.

+ ← Go deeper +
+
1 columntime for 1,000 rows, µs20 columnscost per cell
+ + +
Hand-written selector[rc.16]
[rc.16][rc.16] ns
+ +
ODX Map<T>()[rc.16]
[rc.16][rc.16] ns
+ +
object[] rows[rc.16]
[rc.16][rc.16] ns
+ +
Dapper Query<T>[rc.16]
[rc.16][rc.16] ns
+
+ +

ODX is [rc.16] times faster than Dapper at 1 column, [rc.16] times at 20.
Each line is straight: the cost per cell is the time at 20 columns minus the time at 1 column, divided by the cells added.

+ +
+ + +
+

Pooling

+

Rows go into arrays rented from a pool, and the arrays go back.

+ ← Go deeper +
+
+
await using PooledBuffer<int> buffer = connectionFactory
+    .Command("select id from posts order by id")
+    .Map<int>()
+    .UsePool(ArrayPool<int>.Shared, clearOnReturn: false)
+    .ToPooledBuffer(cancellationToken);
+ + + + ArrayPool + + + buffer + + rent + dispose + + + + The same arrays, reused, not reallocated. Clearing: the next slide. + +
+
+

10,000 int rows, µs. One scale: shorter is better.

+

Collect

+
ArrayPool (ODX design)
9.8
+
Memory<T> chunks
11.7
+
MemoryPool, span per chunk
16.3
+

Read back through the indexer

+
ArrayPool (ODX design)
22.3
+
Memory<T> chunks
48.4
+
+
+ +
+ + +
+

Clearing pooled arrays

+

What is cleared, and why.

+ ← Go deeper + + + + + + + + + + + + yes + no: int, a struct of numbers + true + false + not called + + + Rows hold references? + Post, string, a struct with one + + Always cleared + whatever clearOnReturn says + the pool would keep those objects alive + netstandard2.0: every row type counts + + UsePool(pool, clearOnReturn) + on the query? + Cleared + Kept: opt-out, even with the switch on + ClearPooledArrays switch? + on: cleared + off: kept + + + + + + + + + + read loop, connection held: nothing cleared here + + dispose + only the written part is cleared: + under 128 KB: where it is released + 128 KB or more: a background loop + + + +
+ + +
+

Pipelines

+

Channels and Dataflow over Map<T>(). Use one when something downstream needs it.
For a plain list, use ToListAsync().

+ ← Go deeper +
+
+
ChannelReader<Post> reader = connectionFactory
+    .Command("select * from posts order by id")
+    .Map<Post>()
+    .ToChannelReader(cancellationToken);
+
+await foreach (Post post in reader.ReadAllAsync(cancellationToken))
+{
+    received.Add(post);
+}
+
+
+

In-memory provider, time against a plain loop.
One scale.

+
+
fasterslower
+
+
Channel
+
1,000 rows0.32
+
100 rows0.45
+
1 row1.61
+
BufferBlock
+
1,000 rows0.72
+
100 rows1.10
+
1 row2.56
+

Line: plain loop = 1.00.

+
+
+
+ +
+ +
+ +
← → move · N notes · P presenter · F full screen · T theme · R replay
+

Speaker notes

+
+
00:00
+

+
+ +

+
+ + + + diff --git a/docsite/toc.yml b/docsite/toc.yml index 00ccd09d..d8f3fe37 100644 --- a/docsite/toc.yml +++ b/docsite/toc.yml @@ -3,6 +3,8 @@ - name: API reference href: api/ homepage: api/index.md +- name: Presentation + href: presentation/index.html - name: GitHub href: https://github.com/Open-NET-Libraries/Open.Database.Extensions - name: NuGet