Let’s have:
- $DB an SQL Server database
- $DBSP1 an SQL Server database containing stored procedures referencing $DB
- $DBSP2 is exactly like $DBSP1
- $SP is a stored procedure
Running $SP on $DBSP1 from C# code takes around 1.5s.
Running $SP on $DBSP2 from C# code takes around 0.5s.
The C# code is very simple and use SqlClient with default parameters.
When I execute $SP in an SQL console on both $DBSP1 and $DBSP2, it takes 0.4s.
The only difference between the two code databases is $DBSP1 is in production and is a bit loaded, while $DBSP2 is idle. There is no data in code databases, only stored procedures and views over $DB.
Can someone suggest reasons why this happen? Since all the work happens in $DB which is equally loaded in both cases I would expect performances to be similar.
The difference in speed came from different query plans. $SP is a complicated stored procedure and its initial query plan may vary vastly depending on the first query hitting it. And at this point we were not controlling the first request since right after deploying the $SP, it was published in production.
We tried providing hints about $SP parameters both at $SP levels and query levels, without success. So instead, we warm up the $SP before deploying with well crafted queries known to generate the correct query plan.