Deepesh
Deepesh

Reputation: 5614

Linq Count method and Performance

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

Upvotes: 8

Views: 1794

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503779

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
}

Upvotes: 13

Related Questions