Running code in .NET Core to connect to a SQL Server database seems much slower than in the full .NET Framework. Is this the case? Or I am doing something wrong?
I have SQL Server 2017 on my PC and want to run a simple stored procedure like
CREATE PROCEDURE OneRowSelect
AS
BEGIN
SELECT 1
END
GO
I use SQL Client 4.6.0 to connect to the database, and get the result of this procedure in my code. So I wrote a .Net Standard 2.0 library that provides this code:
private const string connectionString = @"data source=.;initial catalog=TestDB;Integrated Security=SSPI;";
private const string command = @"OneRowSelect";
public static async System.Threading.Tasks.Task Execute()
{
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(command, con)
{
CommandType = CommandType.StoredProcedure
})
{
con.Open();
var data = await cmd.ExecuteReaderAsync();
while (data.Read())
{
var res = data[0];
}
}
}
}
Finally I wrote two projects in .NET Core 2.2 and .NET Framework 4.7.2 and referenced this .NET Standard library in these two projects and log the execution time of Execute
function with Stopwatch
.
My code in these two projects is:
Stopwatch stopwatch = Stopwatch.StartNew();
for (int i = 0; i < repeat; i++)
await Runner.Execute();
stopwatch.Stop();
The result was unbelievable. .NET Core is much slower than .NET Framework in my system. The results are:
- .NET Framework average running time: 2.2ms
- .NET Core average running time: 36.7ms
Am I wrong or is .NET Core this much slower than the .NET Framework?