Skip to content

API for writing parameters without boxing #17446

Open

Description

@roji

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.

Activity

  1. GSPP commented on Jun 1, 2016

    @GSPP

    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.

  2. roji commented on Jun 2, 2016

    @roji
    MemberAuthor

    @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.

  3. karelz commented on Nov 10, 2016

    @karelz
    Member

    @roji (or anyone) can you provide more details what is your plan here?

  4. roji commented on Nov 12, 2016

    @roji
    MemberAuthor

    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.

  5. karelz commented on Nov 12, 2016

    @karelz
    Member

    @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.

  6. danmoseley commented on Dec 27, 2016

    @danmoseley
    Contributor
  7. roji commented on Jul 2, 2017

    @roji
    MemberAuthor

    Can anybody take a look at this? It would be good to know if you guys see this somewhere on your roadmap etc.

  8. karelz commented on Jul 2, 2017

    @karelz
    Member

    @saurabh500 @divega @corivera any opinion here? Can we at least set expectations / timeline when we will have time to look at it? Thanks!

  9. divega commented on Jul 9, 2017

    @divega
    Contributor

    @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

  10. karelz commented on Jul 9, 2017

    @karelz
    Member

    @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!

  11. divega commented on Jul 11, 2017

    @divega
    Contributor

    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.

  12. roji commented on Jul 14, 2017

    @roji
    MemberAuthor

    FYI I'm working on implementing this within Npgsql, I'll be coming back with some info pretty soon.

  13. roji commented on Jul 18, 2017

    @roji
    MemberAuthor

    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 @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>)

    • 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 :)

  14. 33 remaining items

  15. DmitryMak commented on May 24, 2024

    @DmitryMak

    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.

    SQLite and MySql

    public override T GetFieldValue<T>(int ordinal)
    {
    	...
    	if (typeof(T) == typeof(int))
    	    return (T) (object) GetInt32(ordinal);  <-- will generate IL: box [System.Runtime]System.Int32
    	...
    	if (typeof(T) == typeof(string))
    	    return (T) (object) GetString(ordinal);
    	...
    	return (T) GetValue(ordinal);
    }
    

    Do you have examples of DbDataReader.GetFieldValue<T> implementations that don't box?

  16. roji commented on May 24, 2024

    @roji
    MemberAuthor

    Do you have examples of DbDataReader.GetFieldValue implementations that don't box?

    Yes, take a look at Npgsql.

  17. En3Tho commented on May 24, 2024

    @En3Tho
    Contributor

    @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.

  18. Wraith2 commented on May 24, 2024

    @Wraith2
    Contributor
    if (typeof(T) == typeof(int))
    	    return (T) (object) GetInt32(ordinal);

    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).

  19. DmitryMak commented on May 24, 2024

    @DmitryMak

    @En3Tho and @Wraith2 is the (T)(object)val optimization documented anywhere? I only found it here

  20. ejball commented on Mar 11, 2025

    @ejball

    How about doing something similar to DbDataReader.GetFieldValue<T> with the existing (non-generic) DbParameter class?

    public abstract class DbParameter : ...
    {
        ...
        public virtual bool IsNull => Value is null or DBNull;
        public virtual Type? ValueType => Value?.GetType();
        public virtual T GetValue<T>() => (T) Value;
        public virtual void SetValue<T>(T value) => Value = value;
    }

    An optimized implementation could presumably use a discriminated union of 16 bytes to store a Guid or smaller without boxing.

  21. mgravell commented on Mar 20, 2025

    @mgravell
    Contributor

    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

    public override DbParameter CreateParameter<T>(T value)
      => new NpgsqlParameter<T> { TypedValue = value };

    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;
      }

    which npgsql could override:

    public override TValue GetValue<TValue>()
    {
        if (typeof(T) == typeof(TValue))
        {
            var typed = TypedValue;
            return Unsafe.As<T, TValue>(ref typed);
        }
        else
        {
            return base.GetValue<TValue>();
        }
    }
    public override void SetValue<TValue>(TValue value)
    {
        if (typeof(T) == typeof(TValue))
        {
            TypedValue = Unsafe.As<TValue, T>(ref value);
        }
        else
        {
            base.SetValue<TValue>(value);
        }
    }
  22. Wraith2 commented on Mar 20, 2025

    @Wraith2
    Contributor

    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.

  23. mgravell commented on Mar 20, 2025

    @mgravell
    Contributor

    Maybe just an public virtual bool IsDbNull => Value is DBNull; ?

  24. Wraith2 commented on Mar 20, 2025

    @Wraith2
    Contributor

    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.

  25. mgravell commented on Mar 22, 2025

    @mgravell
    Contributor

    @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.

  26. Wraith2 commented on Mar 23, 2025

    @Wraith2
    Contributor

    Sure. I get that. Imagine that we have:

    public SqlParameter<T> : SqlParameter
    {
    	public T TypedValue {get;set;}
    }

    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.

    I'd rather have:

    public SqlParameter<T> : SqlParameter
    {
    	public T TypedValue {get;set;}
    	public bool IsDbNull {get;set;}
    }

    because it

    • removes the need to use the base class value
    • doesn't link langauge and db null
    • 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 (var con = new SqlConnection(conStr))
                using (var cmd = con.CreateCommand())
                {
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    cmd.CommandText = "sp_do_thing";
    
                    var retval = cmd.CreateParameter();
                    retval.ParameterName = "RETURN_VALUE";
                    retval.Direction = ParameterDirection.ReturnValue;
    
                    var output = 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)
                    {
                        int importantValue = output.TypedValue;
                    }
                }
  27. jl0pd commented on Nov 28, 2025

    @jl0pd
    Contributor

    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.

    var boxedInt = new StrongBox<int>();
    
    boxedInt.Value = 7;
    _cmd1.Parameters[0].Value = boxedInt;
    _cmd1.ExecuteNonQuery();
    
    boxedInt.Value = 42;
    _cmd2.Parameters[0].Value = boxedInt;
    _cmd2.ExecuteNonQuery();
  28. Wraith2 commented on Dec 7, 2025

    @Wraith2
    Contributor

    I did prototype something similar with SqlClient, mentioned here and in following comments

  29. rhuijben commented on Mar 25, 2026

    @rhuijben
    Contributor

    I looked at this in parallel (coming from the Dapper angle); I'd like to propose:

    DbParameter DbCommand.CreateParameter<T>()
    void DbParameter.SetValue<T>(T value)
    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-needs-workarea-System.Dataenhancement

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions