Repository navigation
Description
Description
When inserting rows with ExecuteNonQuery() and placeholder parameters, performance
(measured as inserted parameters per second) with the Microsoft.Data.SqlClient v2.1.1
and System.Data.SqlClient providers is progressively impacted from about 50+ parameters
per statement, both for single rows and for multirow batches.
Inserting with 2048 parameters in the statement is up to 7 times slower than with
128 parameters.
The issue is not present when using the System.Data.Odbc provider (or non-SQL Server
providers & databases), and performance is up to 25 times slower (when using 2048 parameters
per statement) than with the ODBC provider.
I've tested with Windows 10, .NET5.0 and a local SQL Server 2019 database, varying the
number of columns from 1 to 1024, and number of rows in each batch from 1 to 1000.
Note: The 'waviness' at 1000 and 2000 parameters is just an effect of the 1000/1024 and 2000/2048
numbers being separated in the graph - see the write-up for details:
The target table is un-indexed and the inserts uses SQL-92 syntax:
INSERT INTO tablename (column-a, [column-b, ...])
VALUES (@r0_c0, [@r0_c1, ...]),
(@r1_c0, [@r1_c1, ...]),
...
While table valued parameters and bulk inserts don't have this issue, they won't
help when inserting a single or just a few very wide rows at a time, so it would be
really useful to have this addressed (or identify any gremlins on my part!)
Please see the full write-up with charts, tables, BenchmarkDotNet info etc. at:
Reproduce
Fully runnable source (using BenchmarkDotNet) and instructions at:
Expected behavior
Using more parameters (beyond 128) in an insert row or batch should increase throughput,
measured as the number of parameters inserted per second, just like it does with
System.Data.Odbc and other non-SqlClient providers.
Technical details
- Microsoft.Data.SqlClient Version="2.1.1"
- System.Data.Odbc Version="5.0.0"
- System.Data.SqlClient Version="4.8.2"
- OS=Windows 10.0.19042
- .NET Core SDK=5.0.103

Activity
[-]Poor INSERT performance with `ExecuteNonQuery()` and many parameters[/-][+]Poor INSERT performance with ExecuteNonQuery() and many parameters[/+]Wraith2 commentedon Mar 9, 2021
What is the real world use case for using so many parameters?
KristianWedberg commentedon Mar 9, 2021
I've personally come across this with:
Wraith2 commentedon Mar 9, 2021
This is likely to be addressed in .net 6 for most major providers with dotnet/runtime#28633
I'll try to take a look at this when I can get some time but I make no promises.
KristianWedberg commentedon Mar 9, 2021
Any help on this issue would be greatly appreciated! As a specific example, I discovered this when benchmarking our ETL library since we use it for (portable) batch inserts. For now, we'll have to advise clients to either switch to the ODBC provider, or use the non-portable bulk insert component. Not the end of the world, but certainly less than ideal.
cheenamalhotra commentedon Mar 9, 2021
Hi @KristianWedberg
Thanks for the comparisons. We'll take a look if some improvements can be made.
roji commentedon Mar 9, 2021
This is an important point - one of the major incentives for having this new batching API was to remove the need to send so many parameters (which regardless of perf imposed an upper limit, since no more than 2100 parameters can be sent).
KristianWedberg commentedon Mar 9, 2021
@roji I'm very much looking forward to the upcoming .NET6 batch API. That said:
roji commentedon Mar 9, 2021
This is very true, though it's probably going to be possible (and advisable) to expose the batching API even for older TFMs - just without implementing the ADO.NET base classes. This would make the API accessible regardless of which TFM you're using (possibly even .NET Framework); that's my plan for Npgsql/PostgreSQL, in any case.
This is true - and at that point it's also a question of how common it is to have such a large number of columns etc.
Wraith2 commentedon Mar 9, 2021
The implementation I've got for SqlClient 3.1/5.0 provides versions of the System.Data base classes needed for this so in theory it can be backported to any TFM the library supports.
One thing i hadn't considered is whether multiple drivers would need to live in the same process, I'll give that some thought and see if i can make the support bits internal.
Of course we've still got to do the work to get the feature into 6.0 and then find the time to get it into SqlClient with encryption support, we might want to light a fire under that @roji 😁
Wraith2 commentedon Mar 9, 2021
Just had a quick look. You're using System.Data.SqlClient. Can you try it with Microsoft.Data.SqlClient from this repository and see if the numbers are any better to start with?
KristianWedberg commentedon Mar 10, 2021
@Wraith2 I'm already using both
Microsoft.Data.SqlClient(the "Microsoft" or "MicrosoftSync" results) andSystem.Data.SqlClient("System" or "SystemSync" results) in the code and in the results. Their performance is identical.Wraith2 commentedon Mar 10, 2021
Ah, I see it now. Had to do some fiddling to profile it and broke something. My mistake.
I've found some interesting areas that I was already aware of but were a way down my list of things to investigate. It's mostly string composition and array resizing overhead. As the parameter count goes up it spends more time allocating and re-allocating to grow and there's not a lot the caller can do about that. It can be reworked to avoid intermediate strings and look at pre-sizing of string builders and target arrays in a few places.
Two things stand out that you could do for the benchmark. Can you keep pre-boxed ints that are used as parameter values around? Their boxing and unboxing is a big source of GC activity. I know that isn't reflectve of real world data but in real world scenarios if you have strongly typed input data of limited or frequently known ranges (bool, small ints) keeping cached boxed versions of some values around and using those will gain you some perf.
If possible reusing SqlParameter instances would be good. They're quite large and you're using a lot of them.
KristianWedberg commentedon Mar 10, 2021
@Wraith2 I've added (and uploaded the code for) using pre-boxed int values to the test.
Here's the original test (boxing of int values, only run 3 batches):
Instead running with pre-boxed int values makes no difference at all:
SqlParameterinstances are already reused across all batches in a test case. For the slowest test cases this was however only 3 batches. Increasing_scaleNumberOfStatementsby a factor of 10 means the cost ofSqlParametercreation is instead amortized over 30 batches (instead of 3). This, together with pre-boxed int values, still makes no difference:So creating
SqlParameters and setting their values is not the bottleneck.For profiling work, you might set
_rowsPerStatementsand_columnsPerRowsto a single value each and comment out the other providers to get a single test case, and increase_scaleNumberOfStatementssufficiently to get long enough run times.59 remaining items
David-Engel commentedon Mar 18, 2021
@Wraith2 I got an exception when parameters hit 512. This was with only
AppContext.SetSwitch("Switch.Microsoft.Data.SqlClient.UseODBCParameterFormat", true);and with that andAppContext.SetSwitch("Switch.Microsoft.Data.SqlClient.OmitNoMetadata", true);Wraith2 commentedon Mar 18, 2021
Interesting. So how do you specify an unbounded nvarchar?
I thought this this:
would become this:
[edit]
perhaps you can only send varchar(max) in plp mode?
David-Engel commentedon Mar 18, 2021
@Wraith2
I think that's correct and it looks like that's what the JDBC driver does:
https://github.com/microsoft/mssql-jdbc/blob/dev/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java#L4615
KristianWedberg commentedon Mar 18, 2021
Now with the latest MDS 3.0.0-dev, and 256 parameters.
OmitNoMetadatamakes no difference, with or withoutUseODBCParameterFormat.varcharversion provides no additional improvement at 256 parameters (379,143 vs. the old 374,091 parameters/s withUseODBCParameterFormat=true).This should obviously be tested with >256 parameters (I got the exception to), which showed a large slowdown with the non-varchar version.
Because of the higher performance, I'll start running with a larger total volume, so these throughput numbers are not directly comparable with previous tests. Again, the interesting bit is if >256 parametes will slow down or not.
Wraith2 commentedon Mar 18, 2021
I'm trying it but it isn't going well. The MetaType for varchar isn't PLP so i'm going to end up looking for size==-1 all over the place and even then it's going to touch a whole lot of places i'm really not happy about possibly breaking. I can only do the sync version because the async code in
TDSExecuteRPCAddParametermeans you can't add any data after you've written the parameter so i don't know how to get the PLP chunk terminator written.Wraith2 commentedon Mar 18, 2021
@KristianWedberg So am I reading the results right that the combination of omitting parameter names and using nvarchar gives better performance than ODBC?
KristianWedberg commentedon Mar 18, 2021
MDS 3.0.0-dev + Omitting parameter names is consistently 5-10% faster than Odbc at 256 parameters.
nvarcharmight or might not help a few percent, hard to say since I can't test them both at the same time.Again -
nvarcharmight help greatly >256 parameters, that we don't know yet.Wraith2 commentedon Mar 18, 2021
You can test longer with this. Horrible hackjob, absolutely don't use it for anything other than this testing and only in sync mode or it'll crash like before.
Microsoft.Data.SqlClient.3.0.0-dev.zip
KristianWedberg commentedon Mar 18, 2021
Success! 🎆
A quick test shows that the latest MDS (and with both switches enabled) scales well all the way to 2048 parameters (at 1,184,713 parameters/s), staying 5-10% faster than Odbc all the way! Full results will take longer.
Note: I did realize I had one issue in my testing setup until now: I was still giving MDS less work (since it used to be up to 20x slower). It might not have been the latest change that did the trick, it could e.g. be just the
UseODBCParameterFormatswitch, I'll go back and check this now.Wraith2 commentedon Mar 18, 2021
OK. Well consider that a proof of concept and now we know it's possible to make it work it'll need to be worked on to make it production capable. I need to learn how the driver is currently handling varchar(max) because it's clearly using some trickery if I've had to add workarounds to make it send a long string correctly. This could take some time.
KristianWedberg commentedon Mar 19, 2021
To sum up the performance measurements:
nvarcharhackjob and the earlier MDSUseODBCParameterFormatwithoutnvarchar(now that I'm running with the same data volume), i.e. thenvarcharhackjob changes are not needed to get great performance.nvarcharhackjob, enabling/disablingOmitNoMetadatamakes no difference, from 1 to 2048 parameters.UseODBCParameterFormatmakes MDS slow down at >32 parameters.Here are repeatable results using the earlier
UseODBCParameterFormatMDS (i.e. withoutnvarcharchanges):So performance looks great.
Functionality wise, I'll highlight that my benchmark only uses each parameter once, in the same order they're written in the query. I'm guessing reusing a named parameter multiple times in the query requires additional testing.
[Edited]
UseODBCParameterFormatmakes MDS slow down at >32 parameters (not >256)Wraith2 commentedon Mar 19, 2021
Oh, that's surprising but welcome.
The parameter format is pretty easy it just needs some agreement on how to implement it so you can use it on a per-command basis. I listed 3 strategies earlier in the thread. That'll be down to @David-Engel and @cheenamalhotra
yes, definitely. I expect it not to work.
That's got to be down to how the name mapping is implemented on the server. I doubt anyone expected it to reach the limit of parameters, that might be something @v-chojas could explore. As I think I said earlier the falloff curve looks list iteration instead of map lookup which makes sense because list tends to be faster than map when items<~100.
David-Engel commentedon Mar 19, 2021
I'm not able to replicate the improved test results with the latest MDS package (hackjob) from @Wraith2 or the previous package. I've triple checked my MDS DLL and I'm pretty sure I'm using the correct one (modified dates line up to the correct times in my build output) and I've tried with and without the UseODBCParameterFormat switch. Performance still falls off around 256 params on all runs I try. 🤔
@KristianWedberg Can you push any changes you made to the test to your repo?
KristianWedberg commentedon Mar 19, 2021
@David-Engel Yes, that will be due to running with too small a data volume for the fast MDS. I've refreshed the benchmark code to address that (for me each test case now takes about 1 second). You'll have to upgrade from MDS 2.1.2.