Search code examples
c#postgresqlnpgsqlstrong-typing

Difference Between Using `NpgsqlParameter<T>` and `AddWithValue` with `NpgsqlDbType`


The Npgsql documentation states that using NpgsqlParameter<T> is better because it is strongly-typed and doesn't strain the garbage collector with useless heap allocations caused by boxing value types.

I have the below two commands that declare the data type to use for a specific parameter:

Not Using NpgsqlParameter<T>:

command.Parameters.AddWithValue("id", NpgsqlTypes.NpgsqlDbType.Integer, 123);

Using NpgsqlParameter<T>:

cmd.Parameters.Add(new NpgsqlParameter<Int32>("id", NpgsqlTypes.NpgsqlDbType.Integer) { TypedValue = 123 });

My question is, is the first command equivalent to the second (won't box the int value) or should I use the second one instead?

I think the first just tells Npgsql what data type to use but will still box the int.


Solution

  • After careful consideration of the input we've received from the community, we have decided to go with NpgsqlParameter<T> with an explicit NpgsqlDbType.

    While we agree that performance hits are indeed very difficult to notice with both options, the explicitness of declaring what you're passing and what you want it to be converted to has convinced us to go with the slightly more verbose option.

    Many thanks to everyone who helped!