You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
api-needs-workAPI needs work before it is approved, it is NOT ready for implementationarea-System.DataenhancementProduct code improvement that does NOT require public API changes/additions
In the current ADO.NET API, writing a parameter to the database involves passing it through an object. This implies a boxing operation, which can create lots of garbage in a scenario where lots of value types (e.g. ints) are written to the database.
A generic subclass of DbParameter could solve this, if properly implemented by providers.
Reacted by Justin Van Patten, Ciprian Khlud, szehetner, Julian Verdurmen, kronic, Brice Lambson, Daniel Smith, Benjamin, besmaili, draganndi and 23 more
Isn't the boxing overhead next to nothing compared to the fixed cost of making a SQL call? I cannot imagine this being an issue even for 1000 parameters.
Reacted by Grigory, egi, kronic, Dave Senn, Juliano Leal Goncalves, JungsooH, Günther Foidl, rampaa and Bert Huijben
@GSPP I'm definitely not talking about the overhead of allocating the memory and copying the value - i.e. the cost of the boxing operation itself. The problem is that boxing allocates an object on the heap, producing potentially large amounts of garbage. This garbage creates pressure on the GC, which can be a problem for some applications. Basically it's a different kind of overhead compared to making an SQL call.
On the read side of things, there's DbDataReader.GetFieldValue<T>() allowing users to generically read values. This allows ADO.NET providers to provide an implementation that doesn't box value types - users can read ints without needless heap allocations.
Unfortunately nothing like this exists on the write side - DbParameter has a object Value property, so writing ints via ADO.NET necessarily implies boxing. This could be resolved by having a generic SqlParameter<T>, whose Value would be of type T. This class could extend could inherit the non-generic SqlParameter for backwards compatibility. It would probably be a good idea to have an IDbParameter<T> interface which would be implemented by the provider-specific generic parameter classes (SqlParameter<T>, NpgsqlParameter<T>).
It would also be necessary to add CreateParameter<T>() to DbProviderFactory to allow portable creation of these new parameters.
Let me know if this makes sense or if you'd like more info.
Reacted by Benjamin, besmaili, Kuba Szostak, egi, Thorsten Sommer, Dave Senn and Cole Tobin
@saurabh500@YoungGah is it sufficient info for you? Or do you need more details?
If we have enough of direction and you agree with it, please remove the "needs more info" and add "up for grabs" label.
@karelz @danmosemsft @saurabh500@corivera I think we should remove the "needs-more-info" label and add "up-for-grabs". This sounds like a good idea to at least explore.
@roji it would be great if you could do some prototyping of this in Npgsql if you haven't already. I suspect it should be possible to do enough to asses the API and make some measurements of the impact without making the actual changes on System.Data.Common. If the change turns very positive results then we can take the next step.
I am not sure about the IDbParameter<T> interface. The extensibility model of ADO.NET has been consistently based on class inheritance since .NET Framework 3.0. The existing interfaces are there only for compatibility so adding new interfaces would be strange. Unless there is really good reason I would try to stick to classes.
@divega sounds good to me - feel free to make such labels changes yourself, as area expert/owner :)
When you mark things "up for grabs", just please try to describe what is needed (next steps) & rough complexity / time investment - see triage rules for details. Thanks!
OK, I've done this in Npgsql (npgsql/npgsql#1639). The question is now how to best add this to ADO.NET as a whole, to allow this to be used in a database-independent way.
General Benefits
Offers a strongly-typed, generic API (TypedValue) alongside the existing weakly-typed object-based API. Promotes type safety, is a more modern API, etc.
Avoids needless boxing when writing value types. Writing a parameter value to the database in Npgsql in now a zero-allocation operation (and in 3.3 ExecuteNonQuery as a whole will probably be zero allocation).
Adding to ADO.NET
This would consist of adding either a new DbParameter<T> abstract base class , inheriting from DbParameter, or an IDbParameter<T> (see discussion below).
In addition, DbProviderFactory would need to be fitted with a new GetParameter<T>() alongside the existing GetParameter() (a GetParameter<T>(PermissionState) may also be necessary). The default implementation of this method would return a shim wrapping the result of the provider's GetParameter(); this would allow providers not providing a real generic parameter implementation to continue working seamlessly.
Base classes vs. interfaces
As @divegamentioned above, ADO.NET APIs are based on base classes rather than interfaces. I worked in both directions for a while to explore what the API would look like, here are some points:
Via base class (DbParameter<T>)
Does not allow for easy code sharing between NpgsqlParameter<T> and NpgsqlParameter - (substantial) logic has to be either duplicated or refactored out somehow.
An internal interface must be introduced to capture the common API between NpgsqlParameter and NpgsqlParameter<T>; this is necessary to allow internal provider code to continue working. This adds considerable clutter to the codebase and is cumbersome.
If any user-facing APIs exist which accept/return an NpgsqlParameter, these also have to be changed (or counterparts added) to accept/return an interface capturing the two parameter types. This interface would need to be distinct from the internal one from the previous point, to avoid exposing internal functionality (so we end up with INpgsqlParameter and INpgsqlInternalParameter).
Via interface (IDbParameter<T>)
Allows the NpgsqlParameter<T> to inherit from NpgsqlParameter. Since both are parameter classes, there's likely to be a lot of shared code; if NpgsqlParameter<T> inherits NpgsqlParameter we only need to add the typed value property plus some minimal generic-specific handling.
In order for IDbParameter<T> to be useful, it must duplicate the API surface of DbParameter, otherwise the user can't manipulate things like Size, Precision.
Conclusions
For provider codebase maintenance and sanity, I'd really prefer it if NpgsqlParameter<T> could extend from NpgsqlParameter. However, the fact that IDbParameter<T> needs to duplicate the DbParameter API is problematic: it would make it impossible to add a method with a default implementation to DbParameter.
On the other hand, I hear that C# 8 will have default interface methods, so maybe it's not so bad :)
Reacted by Yoh Deadfall, Yusuke Ito, Julian Verdurmen, kronic, Benjamin, antiufo, egi, Thorsten Sommer, Geoff McElhanon and Cole Tobin
On the read side of things, there's DbDataReader.GetFieldValue<T>() allowing users to generically read values. This allows ADO.NET providers to provide an implementation that doesn't box value types - users can read ints without needless heap allocations.
Regarding the read side, GetFieldValue<T> is usually implemented with return (T) (object) so it must be boxing as well.
note that this is a special pattern that the jit can recognise and optimize away. In the case where T is int casts would resolve to (int)(object)intValue and the jit can recognise the pattern will box and then unbox and optimize to just intValue.
In language terms it will box. When you run the code and the asm is produced it will probably not box (depending on debug/release, tier0/tier1, (d)PGO, etc).
How about doing something similar to DbDataReader.GetFieldValue<T> with the existing (non-generic) DbParameter class?
publicabstractclassDbParameter:...{...publicvirtualboolIsNull=>Valueisnull or DBNull;publicvirtualType?ValueType=>Value?.GetType();publicvirtualTGetValue<T>()=>(T)Value;publicvirtualvoidSetValue<T>(Tvalue)=>Value=value;}
An optimized implementation could presumably use a discriminated union of 16 bytes to store a Guid or smaller without boxing.
Taking the value as a parameter avoids the need to access .Value. I do wonder whether there should also be some new API on DbParameter, though, in particular I'm thinking about reading out/ref values - maybe:
public abstract class DbParameter
{
+ public virtual T GetValue<T>() => (T)Value;+ public virtual void SetValue<T>(T value) => Value = ((object?)value) ?? DBNull.Value;
}
I like that surface area in general. I think we also need to have a new DbParameter property to tell is whether a strongly typed parameter has been set to null or not without needing to understand the value or its type.
If you had an int somehow not in a box then that would box it. The whole existence of DBNull is a .net 1.0 idea around everything being objects which the ecosystem as largely abandoned as the performance implications became clear.
The null-ness of a value is a separate piece of data from the value. You should only try to touch the value it is known to be not null. I won't object to having an IsDBNull function if that's what we want to call it but I do think that nullness needs to be separate from the value otherwise you end up needing to pick sentinal values which isn't sensible for things like int.
@Wraith2 the idea there is that a subclass like the existing NpgsqlParameter<T> would override this and provide whatever logic it has for null-ness, I.e. "is my value currently coming from TypedValue? Then I'm not null". I'm also assuming that the same subclass would check .Value set for DBNull and set that flag accordingly.
By breaking back compat and unsealing the current SqlParameter.
We can't store the T in the existing object typed location because that might require a box so we're keeping it in a T or similar typed location that can store it without a box. So how do we tell it it's Null. For example an int has default value 0 so do we assume 0 means null? that isn't sensible because we know keeping 0's is very common. We can't compare int against DBNull without a box.
If we assume we have the base class Value location still available we could check if the base class object location contains a DBNull object but that feels pretty weird because we'll need additional logic to make sure that when we set TypedValue we unset base.Value.
Or are you requiring that we link langauge null and db null as concepts? So if an int typed parameter needs to be nullable we enforce the use of int?. I'm not a fan of that idea because the nulls are slightly conceptually different. In sql it's entirely possible to get a null value for a column defined as non-nullable by putting it on the right hand side of a left outer join.
removes the need to reserve an item in range for a null sentinel
allows a pattern where you don't touch Value or TypedValue if IsDbNull is true
follows the same sort of approach as DbReader where null check is separate from value check
I'd want to do something like:
using(varcon=newSqlConnection(conStr))using(varcmd=con.CreateCommand()){cmd.CommandType=System.Data.CommandType.StoredProcedure;cmd.CommandText="sp_do_thing";varretval=cmd.CreateParameter();retval.ParameterName="RETURN_VALUE";retval.Direction=ParameterDirection.ReturnValue;varoutput=cmd.CreateTypedParameter<int>();output.ParameterName="output";output.Direction=ParameterDirection.Output;output.IsDbNull=true;cmd.ExecuteNonQuery();if(retval.Value!=DBNull.Value){// do stuff}if(!output.IsDbNull){intimportantValue=output.TypedValue;}}
DbProvider could special case System.Runtime.CompilerServices.StrongBox<T>. This will allow caller to pool boxed objects, which in turn will allow to write parameters without boxing and API changes.
I looked at this in parallel (coming from the Dapper angle); I'd like to propose:
DbParameterDbCommand.CreateParameter<T>()
void DbParameter.SetValue<T>(Tvalue)
T DbParameter.GetValue<T>()// Maybe a SetDBNull() ?
This may not be the complete solution, but it looks like that it should 100% work against the final solution, and already provides a stable api towards it. Users can already consume it, and other solutions -like npgsql- may already use it to expose earlier optimized paths.
A future extension of the api might then add a more advanced path, but at least we make progress on this path.
Having such a common layer might also get this the attention it needs to get implemented in the providers.
api-needs-workAPI needs work before it is approved, it is NOT ready for implementationarea-System.DataenhancementProduct code improvement that does NOT require public API changes/additions
Activity
GSPP commentedon Jun 1, 2016
Isn't the boxing overhead next to nothing compared to the fixed cost of making a SQL call? I cannot imagine this being an issue even for 1000 parameters.
roji commentedon Jun 2, 2016
@GSPP I'm definitely not talking about the overhead of allocating the memory and copying the value - i.e. the cost of the boxing operation itself. The problem is that boxing allocates an object on the heap, producing potentially large amounts of garbage. This garbage creates pressure on the GC, which can be a problem for some applications. Basically it's a different kind of overhead compared to making an SQL call.
karelz commentedon Nov 10, 2016
@roji (or anyone) can you provide more details what is your plan here?
roji commentedon Nov 12, 2016
On the read side of things, there's
DbDataReader.GetFieldValue<T>()allowing users to generically read values. This allows ADO.NET providers to provide an implementation that doesn't box value types - users can read ints without needless heap allocations.Unfortunately nothing like this exists on the write side - DbParameter has a object
Valueproperty, so writing ints via ADO.NET necessarily implies boxing. This could be resolved by having a genericSqlParameter<T>, whoseValuewould be of type T. This class could extend could inherit the non-genericSqlParameterfor backwards compatibility. It would probably be a good idea to have anIDbParameter<T>interface which would be implemented by the provider-specific generic parameter classes (SqlParameter<T>,NpgsqlParameter<T>).It would also be necessary to add
CreateParameter<T>()to DbProviderFactory to allow portable creation of these new parameters.Let me know if this makes sense or if you'd like more info.
karelz commentedon Nov 12, 2016
@saurabh500 @YoungGah is it sufficient info for you? Or do you need more details?
If we have enough of direction and you agree with it, please remove the "needs more info" and add "up for grabs" label.
danmoseley commentedon Dec 27, 2016
@saurabh500 @YoungGah thoughts?
roji commentedon Jul 2, 2017
Can anybody take a look at this? It would be good to know if you guys see this somewhere on your roadmap etc.
karelz commentedon Jul 2, 2017
@saurabh500 @divega @corivera any opinion here? Can we at least set expectations / timeline when we will have time to look at it? Thanks!
divega commentedon Jul 9, 2017
@karelz @danmosemsft @saurabh500 @corivera I think we should remove the "needs-more-info" label and add "up-for-grabs". This sounds like a good idea to at least explore.
@roji it would be great if you could do some prototyping of this in Npgsql if you haven't already. I suspect it should be possible to do enough to asses the API and make some measurements of the impact without making the actual changes on
System.Data.Common. If the change turns very positive results then we can take the next step.I am not sure about the
IDbParameter<T>interface. The extensibility model of ADO.NET has been consistently based on class inheritance since .NET Framework 3.0. The existing interfaces are there only for compatibility so adding new interfaces would be strange. Unless there is really good reason I would try to stick to classes.cc @ajcvickers
karelz commentedon Jul 9, 2017
@divega sounds good to me - feel free to make such labels changes yourself, as area expert/owner :)
When you mark things "up for grabs", just please try to describe what is needed (next steps) & rough complexity / time investment - see triage rules for details. Thanks!
divega commentedon Jul 11, 2017
Marking as "up for grabs". In order to make progress on this issue we need to do some exploration to understand both the magnitude of the performance impact (e.g. how many allocations we can actually avoid and how that benefits performance) and how to best extend the API. See https://github.com/dotnet/corefx/issues/8955#issuecomment-260108275 and https://github.com/dotnet/corefx/issues/8955#issuecomment-313905218.
roji commentedon Jul 14, 2017
FYI I'm working on implementing this within Npgsql, I'll be coming back with some info pretty soon.
roji commentedon Jul 18, 2017
OK, I've done this in Npgsql (npgsql/npgsql#1639). The question is now how to best add this to ADO.NET as a whole, to allow this to be used in a database-independent way.
General Benefits
TypedValue) alongside the existing weakly-typed object-based API. Promotes type safety, is a more modern API, etc.Adding to ADO.NET
This would consist of adding either a new
DbParameter<T>abstract base class , inheriting fromDbParameter, or anIDbParameter<T>(see discussion below).In addition,
DbProviderFactorywould need to be fitted with a newGetParameter<T>()alongside the existingGetParameter()(aGetParameter<T>(PermissionState)may also be necessary). The default implementation of this method would return a shim wrapping the result of the provider'sGetParameter(); this would allow providers not providing a real generic parameter implementation to continue working seamlessly.Base classes vs. interfaces
As @divega mentioned above, ADO.NET APIs are based on base classes rather than interfaces. I worked in both directions for a while to explore what the API would look like, here are some points:
Via base class (
DbParameter<T>)NpgsqlParameter<T>andNpgsqlParameter- (substantial) logic has to be either duplicated or refactored out somehow.NpgsqlParameterandNpgsqlParameter<T>; this is necessary to allow internal provider code to continue working. This adds considerable clutter to the codebase and is cumbersome.NpgsqlParameter, these also have to be changed (or counterparts added) to accept/return an interface capturing the two parameter types. This interface would need to be distinct from the internal one from the previous point, to avoid exposing internal functionality (so we end up withINpgsqlParameterandINpgsqlInternalParameter).Via interface (
IDbParameter<T>)NpgsqlParameter<T>to inherit fromNpgsqlParameter. Since both are parameter classes, there's likely to be a lot of shared code; ifNpgsqlParameter<T>inheritsNpgsqlParameterwe only need to add the typed value property plus some minimal generic-specific handling.IDbParameter<T>to be useful, it must duplicate the API surface ofDbParameter, otherwise the user can't manipulate things likeSize,Precision.Conclusions
For provider codebase maintenance and sanity, I'd really prefer it if
NpgsqlParameter<T>could extend fromNpgsqlParameter. However, the fact thatIDbParameter<T>needs to duplicate theDbParameterAPI is problematic: it would make it impossible to add a method with a default implementation toDbParameter.On the other hand, I hear that C# 8 will have default interface methods, so maybe it's not so bad :)
33 remaining items
DmitryMak commentedon May 24, 2024
Regarding the read side,
GetFieldValue<T>is usually implemented withreturn (T) (object)so it must be boxing as well.SQLite and MySql
Do you have examples of
DbDataReader.GetFieldValue<T>implementations that don't box?roji commentedon May 24, 2024
Yes, take a look at Npgsql.
En3Tho commentedon May 24, 2024
@DmitryMak When running on CLR, patterns you've shown are recognized by jit compiler and boxing is automatically removed.
It will still box on other runtimes like mono for example.
If you've hit a pattern like that (generic method with typeof checks then box-unbox sequence) that still boxes then you should file an issue I guess.
Wraith2 commentedon May 24, 2024
note that this is a special pattern that the jit can recognise and optimize away. In the case where T is int casts would resolve to
(int)(object)intValueand the jit can recognise the pattern will box and then unbox and optimize to justintValue.In language terms it will box. When you run the code and the asm is produced it will probably not box (depending on debug/release, tier0/tier1, (d)PGO, etc).
DmitryMak commentedon May 24, 2024
@En3Tho and @Wraith2 is the
(T)(object)valoptimization documented anywhere? I only found it hereejball commentedon Mar 11, 2025
How about doing something similar to
DbDataReader.GetFieldValue<T>with the existing (non-generic)DbParameterclass?An optimized implementation could presumably use a discriminated union of 16 bytes to store a
Guidor smaller without boxing.mgravell commentedon Mar 20, 2025
I looked at this in parallel (coming from the Dapper angle); I'd like to propose:
public abstract class DbCommand { + public virtual DbParameter CreateParameter<T>(T value) + { + var param = CreateParameter(); + param.Value = ((object?)value) ?? DBNull.Value; + return param; + } } public abstract class DbBatchCommand { + public virtual DbParameter CreateParameter<T>(T value) + { + var param = CreateParameter(); + param.Value = ((object?)value) ?? DBNull.Value; + return param; + } }This is can then be overridden if providers want to, for example npgsql can do
Taking the value as a parameter avoids the need to access
.Value. I do wonder whether there should also be some new API onDbParameter, though, in particular I'm thinking about readingout/refvalues - maybe:public abstract class DbParameter { + public virtual T GetValue<T>() => (T)Value; + public virtual void SetValue<T>(T value) => Value = ((object?)value) ?? DBNull.Value; }which npgsql could override:
Wraith2 commentedon Mar 20, 2025
I like that surface area in general. I think we also need to have a new DbParameter property to tell is whether a strongly typed parameter has been set to null or not without needing to understand the value or its type.
mgravell commentedon Mar 20, 2025
Maybe just an
public virtual bool IsDbNull => Value is DBNull;?Wraith2 commentedon Mar 20, 2025
If you had an int somehow not in a box then that would box it. The whole existence of DBNull is a .net 1.0 idea around everything being objects which the ecosystem as largely abandoned as the performance implications became clear.
The null-ness of a value is a separate piece of data from the value. You should only try to touch the value it is known to be not null. I won't object to having an IsDBNull function if that's what we want to call it but I do think that nullness needs to be separate from the value otherwise you end up needing to pick sentinal values which isn't sensible for things like int.
mgravell commentedon Mar 22, 2025
@Wraith2 the idea there is that a subclass like the existing
NpgsqlParameter<T>wouldoverridethis and provide whatever logic it has for null-ness, I.e. "is my value currently coming fromTypedValue? Then I'm not null". I'm also assuming that the same subclass would check.Value setforDBNulland set that flag accordingly.Wraith2 commentedon Mar 23, 2025
Sure. I get that. Imagine that we have:
By breaking back compat and unsealing the current SqlParameter.
We can't store the T in the existing
objecttyped location because that might require a box so we're keeping it in aTor similar typed location that can store it without a box. So how do we tell it it'sNull. For example an int has default value 0 so do we assume 0 means null? that isn't sensible because we know keeping 0's is very common. We can't compare int against DBNull without a box.If we assume we have the base class Value location still available we could check if the base class object location contains a DBNull object but that feels pretty weird because we'll need additional logic to make sure that when we set TypedValue we unset base.Value.
Or are you requiring that we link langauge null and db null as concepts? So if an
inttyped parameter needs to be nullable we enforce the use ofint?. I'm not a fan of that idea because the nulls are slightly conceptually different. In sql it's entirely possible to get a null value for a column defined as non-nullable by putting it on the right hand side of a left outer join.I'd rather have:
because it
I'd want to do something like:
jl0pd commentedon Nov 28, 2025
DbProvider could special case
System.Runtime.CompilerServices.StrongBox<T>. This will allow caller to pool boxed objects, which in turn will allow to write parameters without boxing and API changes.Wraith2 commentedon Dec 7, 2025
I did prototype something similar with SqlClient, mentioned here and in following comments
rhuijben commentedon Mar 25, 2026
This may not be the complete solution, but it looks like that it should 100% work against the final solution, and already provides a stable api towards it. Users can already consume it, and other solutions -like npgsql- may already use it to expose earlier optimized paths.
A future extension of the api might then add a more advanced path, but at least we make progress on this path.
Having such a common layer might also get this the attention it needs to get implemented in the providers.