Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Count method and Performance

Tags:

linq

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

like image 893
Deepesh Avatar asked Sep 16 '11 13:09

Deepesh


People also ask

Is Linq good for performance?

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.

Is any faster than count?

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.

Which is faster any or count C#?

Any() is ALWAYS faster than . Count() > 0 ).

Is Linq faster than for each?

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 .


1 Answers

It's hard to say for sure, as we don't know what getData is, but:

  • Yes, potentially they'll be completely separate operations
  • In general, use Any() instead of Count() > 0; it can be a lot more efficient, particularly in LINQ to Objects
  • Calling ToList is going to be relatively cheap when it's empty - just do it if you need a list
  • If you don't really need it in a list, just iterate anyway (if there's no data, you'll never get into the loop body)
  • Where will never return null

In other words, I'd probably write:

foreach (Obj xyz in objData.Where(obj => !obj.isDelete))
{
   //some operation
}
like image 184
Jon Skeet Avatar answered Dec 09 '22 22:12

Jon Skeet