c# - 与 SMSS 相比,从 ADO.NET 执行具有相同查询计划的相同查询需要大约 10 倍的时间

标签 c# sql-server performance tsql ado.net

我的查询相当复杂,但我对其进行了简化以找出这个问题,现在它是一个在 SQL Server 2014 数据库上运行的简单 JOIN。查询是:

SELECT * FROM SportsCars as sc INNER JOIN Cars AS c ON c.CarID = sc.CarID WHERE c.Type = 1

当我从 SMSS 运行此查询并在 SQL Profiler 中观察它时,执行大约需要 350 毫秒。当我使用 Entity Framework 或 ADO.NET 在我的应用程序中运行相同的查询时(我都试过了)。执行需要 4500ms。

ADO.NET 代码:

using (var connection = new SqlConnection(connectionString))
{
    connection.Open();
    var cmdA = new SqlCommand("SET ARITHABORT ON", connection);
    cmdA.ExecuteNonQuery();

    var query = "SELECT * FROM SportsCars as sc INNER JOIN Cars AS c ON c.CarID = sc.CarID WHERE c.Type = 1";
    var cmd = new SqlCommand(query, connection);
    cmd.ExecuteNonQuery()
}

我进行了广泛的 Google 搜索并找到了 this awesome article和几个 StackOverflow 问题(herehere)。为了使两个查询的 session 参数相同,我在 ADO.NET 中调用了 SET ARITHABORT ON,但没有任何区别。这是一个直接的 SQL 查询,因此不存在参数嗅探问题。我已将查询和索引简化为此测试的最基本形式。服务器上没有其他任何东西在运行,并且在测试期间没有任何其他东西可以访问数据库。 Cars 或 SportsCars 表中没有计算列,只有 INT 和 VARCHAR。

SportsCars 表有大约 170k 条记录和 4 列,Cars 表有大约 120 万条记录和 7 列。生成的数据集(SportsCars of Type=1)有大约 2600 条记录和 11 列。我在 Cars 表的 [Type] 列上有一个非聚集索引,其中包含 cars 表的所有列。并且这两个表在 CarID 列上都有一个聚集索引。两个表上都不存在其他索引。在这两种情况下,我都以相同的数据库用户身份运行。

当我在 SQL Profiler 中查看数据时,我发现两个查询都使用完全相同且非常简单的查询计划。在 SQL Profiler 中,我使用了 Performance Event Class 和 ShowPlan XML Statistics Profile,我认为这是监视和捕获实际执行计划的合适事件。两个查询的读取次数相同 (2596)。

使用完全相同的查询计划的两个完全相同的查询如何在 ADO.NET 和 SMSS 中花费 10 倍的时间?

最佳答案

想通了:

因为我使用的是 Entity Framework,所以我的应用程序中的连接字符串具有 MultipleActiveResultSets=True。当我从连接字符串中删除它时,查询在 ADO.NET 和 SSMS 中具有相同的性能。

显然此设置存在问题,导致查询在通过 WAN 连接到 SQL Server 时响应缓慢。我找到了 this link还有这个comment :

MARS uses "firehose mode" to retrieve data. Firehose mode means that the server will produce data as fast as possible. This also means that your client application must receive inbound data at the same speed as it comes in. If it doesn't the data storage buffers on the server will fill up and the processing will stop until those buffers empty.

So what? You may ask... But as long as the processing is stopped the resources on the SQL server are in use and are tied up. This includes the worker thread, schema and data locks, memory, etc. So it is crucial that your client application consumes the inbound results as quickly as they arrive.

我必须在 Entity Framework 中使用此设置,否则延迟加载会产生异常。所以我将不得不想出一些其他的解决方法。但至少我现在明白了这个问题。

关于c# - 与 SMSS 相比,从 ADO.NET 执行具有相同查询计划的相同查询需要大约 10 倍的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27351113/

相关文章:

c# - Autofac 作为 AWS Lambda Serverless ASP.NET Core 3.1 Web API 中的 IoC 容器

sql - 将 varchar 数据类型转换为 datetime 数据类型导致值超出范围。 SQL 服务器

.net - HTTPListener与 native HTTP性能

Javascript 调用函数或内联代码?

c# - String.Equals(string1.Substring(0, x), string2) 比 string1.StartsWith(string2) 好吗?

c# - 如何在 xaml 中填充宽度的窗口中绘制一条线

c# - 堆栈 <> C# 中的实现

sql-server - SQL Server varchar(max) 无法正常工作

python - 将 django-mssql 连接到 mssql 服务器(azure)

mysql - 在MySQL看来,是用union开始更快还是用union结束更快呢?