I am using Linq extensively in my project, so far performance is good, i have just one doubt if i have used Linq something like this
var getData = objData.where(obj => obj.isDelete ==false)
if (getData != null && getData.Count() > 0)
foreach(xyz as obj in getdata.ToList())
{
//some operation
}
Does getData.Count() and getdata.ToList() performs two different fetches on object? Or as per deffer loading concept when getData.Count() is executed then no operation is performed for .ToList.
If not then should i remove Count condition, will it improve the performance?
I am using Enterprise Library 5.0 acessor methods to get data from DB List lstpack = new List();
var accessor = _sqlDatabase.CreateSprocAccessor<PackageForClient>("PackageForClientApp", MapBuilder<PackageForClient>
.MapAllProperties()
.Build()
);
var Data = accessor.Execute(startdate, enddate,beinh);
if (Data != null) //&& Data.Count() > 0 //This has been removed as it is doing an extra fetch
lstpack = Data.ToList<PackageForClient>();
Now returning the list
It is slightly slowerLINQ syntax is typically less efficient than a foreach loop. It's good to be aware of any performance tradeoff that might occur when you use LINQ to improve the readability of your code. And if you'd like to measure the performance difference, you can use a tool like BenchmarkDotNet to do so.
Without the condition, both methods are pretty close, with the Any() method being slightly faster. On the other hand, we can see that the Any() method with the condition performs much better as it takes 2,734 ns, while the Count() method with the condition takes 5,505 ns.
Any() is ALWAYS faster than . Count() > 0 ).
Any(), definitely performs slower than the foreach. All these inaccurate answers and comments. No, LINQ iterators are not and will never be faster than foreach .
It's hard to say for sure, as we don't know what getData
is, but:
Any()
instead of Count() > 0
; it can be a lot more efficient, particularly in LINQ to ObjectsToList
is going to be relatively cheap when it's empty - just do it if you need a listWhere
will never return nullIn other words, I'd probably write:
foreach (Obj xyz in objData.Where(obj => !obj.isDelete))
{
//some operation
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With