bool isEmployeeFound;
DbContext DatabaseContext = new DbContext(DatabaseConnectionString);
using (DatabaseContext )
{
isEmployeeFound= DatabaseContext .Persons.Any(p => p.ExternalId == "123"); -- 1st statement
isEmployeeFound= DatabaseContext .Persons.Count(p => p.ExternalId == "123") > 0; --2nd statement
}
我的要求是只检查给定的员工 ID;是否存在于表中。我不希望表中的行只是真或假。我使用的是 Entity Framework 而不是 LINQ to Objects。
我一直在阅读有关 Any 和 Count 的内容,但有点无法决定;我应该使用哪一个?如上所示,在我的代码中,我应该使用第 1 条还是第 2 条语句?
我读到使用 Any(它在 SQL 中转换为 Exists)更快,因为一旦满足条件,它就会停止迭代并返回结果,而 Count()(它在 SQL 中转换为 select Count(*))迭代所有然后返回结果。然而这篇文章Which method performs better: .Any() vs .Count() > 0? 说 Count() 针对 Linq to objects 进行了优化,它的性能优于 任何。
我确实探索了更多并尝试使用下面的代码片段获取时间
using (var _dbContext = new DbContext())
{
string caregiverId = "2301001";
string clientPhoneNumber = "9795397674";
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
bool iscareGiverFoundWithAny = _dbContext.Persons.Any(p => p.ExternalId == caregiverId);
bool isClientPhoneNumberFoundWithAny = _dbContext.PhoneNumbers.Any(ph => ph.Number == clientPhoneNumber);
var testResult1 = stopwatch.Elapsed;
stopwatch.Restart();
bool iscareGiverFoundWithCountExt = _dbContext.Persons.Count(p => p.ExternalId == caregiverId) > 0;
bool isClientPhoneNumberFoundWithCountExt = _dbContext.PhoneNumbers.Count(ph => ph.Number == clientPhoneNumber) > 0;
var testResult2 = stopwatch.Elapsed;
stopwatch.Stop();
Console.WriteLine("Any " + testResult2.TotalSeconds); -- value for this line is coming as 0.0276239
Console.WriteLine("Count Ext. " + testResult3.TotalSeconds); -- value for this line is coming as 0.0054292
Console.ReadLine();
}
在运行上面的代码时,它显示 Count 更快。我很困惑。
有什么想法吗?
最佳答案
简短的回答:坚持使用 Any()。
您可以安全地忽略您正在引用的帖子,因为它不是特定于 Entity Framework 的。在简单集合之上使用 LINQ 时,是的,可能还有其他注意事项。但是当使用 LINQ 查询数据库时,您希望避免不必要地遍历额外的数据库记录。
在这种情况下,您说 Count() 被证明比 Any() 快。但您体验到的差异是如此之小,至少在数据库性能方面如此,您可以说在这种情况下您获得了同等的性能。
实际上,如果您的表很小,或者如果您正在搜索的列已正确索引并返回很少的记录,那么您可以预期 Any() 和 Count() 的性能非常相似。
但假设您有一个大表,并且您的 ExternalId 列没有索引,那么您将不可避免地注意到 Any() 的性能大大优于 Count()。
要点:最佳情况(如果您的数据模型已优化),这两个选项的性能可能相似。最坏的情况下,Any() 绝对会胜过 Count()。
除非 EF 引入了严重的 SQL 生成错误,否则永远不会出现 Count() 的性能大大优于 Any() 的情况。所以为了安全起见,我建议您坚持使用 Any()。
关于c# - Entity Framework 中的任何 Vs 计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30619509/