Repository navigation
Description
With https://github.com/dotnet/corefx/issues/27445 allowing elimination of allocations in asynchronously-executing async methods, we should look into adding ValueTask-returning counterparts to ADO.NET. This would potentially allow zero-allocation database access.
Here are the current async methods:
Task DbConnection.OpenAsync(...);
Task<DbDataReader> DbCommand.ExecuteReaderAsync(...);
Task<DbDataReader> DbCommand.ExecuteDbDataReaderAsync(...);
Task<object> DbCommand.ExecuteScalarAsync(...);
Task DbCommand.ExecuteNonQueryAsync(...);
Task<bool> DbDataReader.ReadAsync(...);
Task<T> DbDataReader.GetFieldValueAsync<T>(...);
Task<bool> DbDataReader.IsDBNullAsync(...);Notes:
-
Naming the new methods is going to be complicated. Some parts of corefx are lucky in that they're introducing
ValueTask<T>overloads along withSpan<T>(e.g. Stream), but ADO.NET has no such upcoming parameter changes/additions. Since there can't be yet another overload that only differs on the return type, and the "standard" name with just theAsyncsuffix is taken, we need to come up with a new naming pattern. -
There are some missing async methods in ADO.NET in general (e.g.
DbCommand.Prepare(),DbConnection.BeginTransactionAsync(...),DbTransaction.CommitAsync(...)...). These can be added directly with return valueValueTask<T>(covered by issue https://github.com/dotnet/corefx/issues/35012). Naming of these new methods should probably be decided in the context of whatever new naming pattern we use for theValueTask<T>returning variants of the existing async methods. -
Also note that async APIs that return
TaskorTask<bool>(such asReadAsync()andIsDBNullAsync()) can be implemented to return cachedTask<T>instances when they complete synchronously to gain efficiency instead of adoptingValueTask<TResult>. This mitigates the need forValueTask<T>returning variants for most APIs. Also, in terms of allocations, the advantage ofValueTask<T>is much greater the more fine grained the async methods are. -
Compatibility for providers: It seems desirable to offer a default implementation of the Task-based method that calls
AsTask()on theValueTask<TResult>instance returned by the new API, so that new providers don't need to implement the oldTask<TResult>version of the API but instead only implement the more efficientValueTask<TResult>version. It also seems good not to force existing providers to switch.
**Updated by @divega on 1/13/2019 to consolidate with https://github.com/dotnet/corefx/issues/15011.
Activity
divega commentedon Mar 3, 2018
System.Data Triage: We should consider this, but since it isn’t for 2.1, moving to future.
davidfowl commentedon Mar 3, 2018
Are any of these methods streaming? Would IAsyncEnumerable be interesting here?
divega commentedon Mar 3, 2018
@davidfowl
DbDataReader.Readis streaming. The current API does not resembleIEnumerable(possibly because it predates it 😄), but the new API could useIAsyncEnumerableif the timing is good.See this was mentioned on aspnet/DataAccessPerformance#32.
roji commentedon Mar 3, 2018
DbDataReader implement IEnumerable, exposing rows as DbDataRecord. It's an old API (non-generic, sync-only), and the default implementation, which uses DbEnumerator, is also pretty inefficient: it calls
DbDataReader.GetValues(), which copies the row's values into an object[] (which gets allocated on each MoveNext()...).But I actually don't really see a reason not to also have DbDataReader implement IAsyncEnumerable... It could provide a modern and efficient way to stream over the the rows of a resultset. Opened dotnet/corefx#27684 to track.
GSPP commentedon Apr 2, 2018
Is the allocation overhead really significant when opening a connection or executing a reader? Executing
select nullagainst SQL Server on the same machine over shared memory and using synchronous IO takes about 200us. This already is so much more than allocating a few objects and collecting them.Adding ValueTask versions for reading rows and fields might be valuable.
roji commentedon Apr 2, 2018
You're right that when
OpenAsync()returns asynchronously (i.e. a physical open or wait), the memory overhead is probably negligible. For synchronous invocations (no I/O, pooled idle connection is returned) there is no memory overhead, sinceOpenAsync()returns a non-generic task which can be cached. So I agree this has more value forDbDataReadet.Read().However, don't forget that ADO.NET is sometimes used to access databases like Sqlite, where the physical open can be much much faster (no networking), so it could be significant there.
Grauenwolf commentedon Nov 7, 2018
ValueTask DblDataReader.GetFieldValueAsync(...);
ValueTask DbDataReader.IsDBNullAsync(...);
If we're going to touch this, we might as well fix the IsDBNull problem at the same time. Currently we need to make two calls, once to check for nulls and again to actually read the value.
When I profile my ORM, IsDBNull is often flagged as most expensive operation in aggregate.(EDIT: this is no longer true.)We can probably make it a lot more convenient
efficientwith methods such asValueTask<T?> DblDataReader.GetFieldValueOrNullAsync(...);
roji commentedon Nov 7, 2018
Depending on the ADO.NET provider implementation, calling
IsDBNull()separately fromGetFieldValue<T>()isn't necessary a big perf problem (I'm not sure it's the case with Npgsql). But introducing something likeGetFieldValueOrNull()(and its async counterpart) would be a good idea regardless, if only for improving the API/usability.Note that using the async versions of these methods is probably a bad idea unless
CommandBehavior.SequentialAccessis specified, since the entire row is pretty much guaranteed to be buffered in memory anyway...Grauenwolf commentedon Nov 8, 2018
You're right. When I last benchmarked it on .NET Framework a year or two ago it was a major issue. Now it's barely visible in the performance profiler.
Grauenwolf commentedon Nov 8, 2018
Still, it would be nice for those who are using ADO.NET directly to not have to write those checks.
roji commentedon Nov 8, 2018
Absolutely, it would be great if ADO.NET got a bit of a face-lift in terms of API usability, regardless of any perf aspects...
Good to know that perf-wise things are better, there have been a lot of changes in recent two years.
GSPP commentedon Nov 8, 2018
If this proposed deserialization API is implemented then the ADO.NET APIs will not be very chatty. There will be less of a need for
ValueTask.ValueTaskcan be used internally.divega commentedon Nov 9, 2018
@roji @Grauenwolf I would like us to track the idea of GetFieldValueOrNull[Async] as a separate issue. Would you like to create it?
Grauenwolf commentedon Nov 9, 2018
I haven't read the underlying code yet, so I think someone else would be better suited to proposing an API.
MgSam commentedon Nov 9, 2018
I vote against mixing
ValueTaskandTaskreturn types arbitrarily based solely on the age of the method.ValueTaskreturn types should only be highly targeted to methods likely to be called over and over.I do agree
BeginTransactionAsyncandCommitTransactionAsyncare needed, though they should not beValueTask.39 remaining items
dotnet-policy-service commentedon Jan 6, 2025
This issue will now be closed since it had been marked
no-recent-activitybut received no further activity in the past 14 days. It is still possible to reopen or comment on the issue, but please note that the issue will be locked if it remains inactive for another 30 days.Wraith2 commentedon Jan 6, 2025
I'm not sure if we want this closed. It would be very useful to have ValueTask field value getters at least. We can make them provider specific if we need to but it would be preferable not to. The problem is naming. The name
GetFieldValueValueTaskAsync<T>is clumsy and the best alternative I can come up with isGetValueTask2Async<T>roji commentedon Jan 7, 2025
Reopening to keep this on our radar... FWIW I think GetFieldValueAsync() is generally rarely needed, since it's mainly useful when CommandBehavior.SequentialAccess is specified (i.e. big rows being streamed); in the regular/default mode, the entire row is buffered anyway (and can be read in random order), so using the sync API (GetFieldValue) is perfectly fine.
But yeah, for sequential access mode we should indeed have a non-allocating API - which would ideally also improve the usability around nulls as well.
Wraith2 commentedon Jan 7, 2025
The knowledge you need to have to understand that using GetFieldValue is probably ok is quite high. Enabling users in async contexts to casually use
await GetFieldValue2Asyncwithout exposing them to the current high costs of Task versions is desirable.roji commentedon Jan 7, 2025
Fair enough, though I wouldn't call the costs of Task allocations "high" for the typical application. In any case I agree this is a good thing to do.