LINQ Performance Issue只有几百条记录

时间:2012-03-30 09:09:56

标签: linq

在下面的代码中,我评论了我的页面向下调低的行。我做了一些速度测试,以揭示CONTAINS LINQ表达式是问题。

有没有人知道如何更改这一行,以便更有效地使用其他内容。我也很好奇它为什么这么慢。

任何想法(提前感谢):

    var allWaste = _securityRepository.FindAllWaste(userId, SystemType.W);
    var allWasteIndicatorItems = _securityRepository.FindAllWasteIndicatorItems();

    // First get all WASTE RECORDS
    var searchResults = (from s in allWaste
                         join x in allWasteIndicatorItems on s.WasteId equals x.WasteId
                         where (s.Description.Contains(searchText)
                         && s.Site.SiteDescription.EndsWith(searchTextSite)
                         && (s.CollectedDate >= startDate && s.CollectedDate <= endDate))
                         && x.EWC.EndsWith(searchTextEWC)
                         select s).Distinct();

    var results = searchResults.AsEnumerable();

    if (hazardous != "-1") 
    {
        // User has requested to filter on Hazardous or Non Hazardous only rather than Show All
        var HazardousBoolFiltered = (from we in _db.WasteIndicatorItems
        .Join(_db.WasteIndicators, wii => wii.WasteIndicatorId, wi => wi.WasteIndicatorId, (wii, wi) => new { wasteid = wii.WasteId, wasteindicatorid = wii.WasteIndicatorId, hazardtypeid = wi.HazardTypeId })
        .Join(_db.HazardTypes, w => w.hazardtypeid, h => h.HazardTypeId, (w, h) => new { wasteid = w.wasteid, hazardous = h.Hazardous })
        .GroupBy(g => new { g.wasteid, g.hazardous })
        .Where(g => g.Key.hazardous == true && g.Count() >= 1)
                                     select we).AsEnumerable(); // THIS IS FAST

        // Now join the 2 object to eliminate all the keys that do not apply
        if (bHazardous)
            results = (from r in results join x in HazardousBoolFiltered on r.WasteId equals x.Key.wasteid select r).AsEnumerable(); //This is FAST
        else
            results = (from r in results.Where(x => !HazardousBoolFiltered
                .Select(y => y.Key.wasteid).Contains(x.WasteId)) select r).AsEnumerable(); // This is DOG SLOW 10-15 seconds !--- THIS IS SLOWING EXECUTION by 10 times --!


    }


    return results.AsQueryable();

2 个答案:

答案 0 :(得分:1)

我建议使用智能检查或log4net等日志/跟踪框架与调试文本编写器结合使用。 http://www.codesprouts.com/post/View-LINQ-To-SQL-Statements-Using-A-Debug-TextWriter.aspx

另一种可能性是使用sql server profiler并查看sql linq2sql生成的内容。

另一种非常好的方法是将mvc mini profiler与Profiled DB Connection和SqlFormatters.SqlServerFormatter结合使用。

答案 1 :(得分:0)

尝试AnyMSDN

试试这个:

results = (from r in results
    .Where(x => !HazardousBoolFiltered
        .Any(y => y.Key.wasteid == r.WasteId)))
    .AsEnumerable()

Count

results = (from r in results
    .Where(x => HazardousBoolFiltered
        .Count(y => y.Key.wasteid == r.WasteId) == 0))
    .AsEnumerable()