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),
});
}
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);
So plain .Map<T>() reaches the ceiling. Nothing to write.
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 databases, 10,000 rows of 20 columns. Grey: a plain loop reading every value. On top: each library.
SQL Server LocalDB plain loop: [rc.16] ms
ODX Map<T>()+[rc.16] ms
Hand-written+[rc.16] ms
Dapper.AOT+[rc.16] ms
Dapper+[rc.16] ms
SQLite file plain loop: [rc.16] ms
ODX Map<T>()+[rc.16] ms
Hand-written+[rc.16] ms
Dapper.AOT+[rc.16] ms
Dapper+[rc.16] ms
Memory: Dapper allocates [rc.16] more than ODX on SQL Server, [rc.16] more on SQLite.
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);
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);
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);
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.
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.
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.
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.
Stop early
CancelOnEarlyStop(): opt in, when the query returns far more rows than you need.
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
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
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
object[] rows at one column. AsyncReads() against the default.
Channels and Dataflow for a single row, and a BufferBlock at 100 rows.
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
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.
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.
await using PooledBuffer<int> buffer = connectionFactory
.Command("select id from posts order by id")
.Map<int>()
.UsePool(ArrayPool<int>.Shared, clearOnReturn: false)
.ToPooledBuffer(cancellationToken);
10,000 int rows, µs. One scale: shorter is better.
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