Linq to Sql和T-SQL性能差异

时间:2012-08-08 11:53:47

标签: asp.net-mvc performance linq-to-sql

我有一个MVC网站,它提供了一个来自SQL Server数据库的分页数据记录列表。 UI允许用户根据许多不同的标准过滤返回的数据,例如,电子邮件地址。这是一段代码:

Stopwatch stopwatch = new Stopwatch();

var temp = SubscriberDB
   .GetSubscribers(model.Filter, model.PagingInfo);

// Inspect SQL expression here

stopwatch.Start();
model.Subscribers = temp.ToList();
stopwatch.Stop();     // 9 seconds plus compared to < 1 second in Query Analyzer

运行此代码时,StopWatch显示执行时间约为9秒。如果我捕获生成的SQL表达式(就在使用.ToList()方法计算它之前)并将其作为对SQL Server Management Studio的查询,那么执行时间将减少到不到1秒。这里参考的是生成的SQL表达式:

SELECT [t2].[SubscriberId], [t2].[Email], [t3].[Reference] AS [DataSet], [t4].[Reference] AS [DataSource], [t2].[Created]
FROM (
    SELECT [t1].[SubscriberId], [t1].[SubscriberDataSetId], [t1].[SubscriberDataSourceId], [t1].[Email], [t1].[Created], [t1].[ROW_NUMBER]
    FROM (
        SELECT ROW_NUMBER() OVER (ORDER BY [t0].[Email], [t0].[SubscriberDataSetId]) AS [ROW_NUMBER], [t0].[SubscriberId], [t0].[SubscriberDataSetId], [t0].[SubscriberDataSourceId], [t0].[Email], [t0].[Created]
        FROM [dbo].[inbox_Subscriber] AS [t0]
        WHERE [t0].[Email] LIKE '%_EMAIL_ADDRESS_%'
        ) AS [t1]
    WHERE [t1].[ROW_NUMBER] BETWEEN 0 + 1 AND 0 + 20
    ) AS [t2]
INNER JOIN [dbo].[inbox_SubscriberDataSet] AS [t3] ON [t3].[SubscriberDataSetId] = [t2].[SubscriberDataSetId]
INNER JOIN [dbo].[inbox_SubscriberDataSource] AS [t4] ON [t4].[SubscriberDataSourceId] = [t2].[SubscriberDataSourceId]
ORDER BY [t2].[ROW_NUMBER]

如果我删除了email filter子句,那么控制器的StopWatch会在不到1秒的时间内向SQL Management Studio查询返回类似的响应时间 - 所以我假设SQL管道的基本接口工作正常并且问题是对Linq表达式的评价。我还要提一下,这是一个非常庞大的数据库,在订阅者表中有超过1M行。

任何人都可以说明为什么应该有这么高的(x10)性能差异以及如果有什么办法可以解决这个问题呢?

1 个答案:

答案 0 :(得分:1)

对此不太确定。具有完整类似的1M行可以花费安静的时间。电子邮件被编入索引吗你能用Email%而不是%Email%运行查询,看看会发生什么?