Vadim Rapp
Vadim Rapp

Reputation: 75

Linq First or Single have drastic effect on performance

I found that adding .First() after Take(1) in the following LINQ query

{
    var qty= (from ii in Inventory
               where ii.Part == "abc" & ii.Zone == "xyz"
               select ii.Qty).Take(1);
}

increases execution time several thousand times. Same with .Single(). Wondering why. Note that even without First the result already has only one record.

Full code:

namespace ConsoleApp1
{
    class SurroundingClass
    {
        class part
        {
            public string id { get; set; }
            public string zone { get; set; }
            public int qty { get; set; }
        }
        public static void Main()
        {
            List<part> inventory = new List<part>();
            for (var i = 1; i <= 50000; i++)
                inventory.Add(new part() { id = System.Convert.ToString(i), zone = System.Convert.ToString(i), qty = 3 });
            object qty1;
            DateTime d0 = DateTime.Now;
            for (var i = 1; i <= 20000; i++)
                qty1 = (from x in inventory
                        where x.id == "40000" & x.zone == "40000"
                        select x.qty).Take(1).First();
            DateTime d1 = DateTime.Now;
            Console.WriteLine(((TimeSpan)(d1 - d0)).Seconds);
        }
    }
}

Upvotes: 0

Views: 68

Answers (2)

Nguyễn Văn Phong
Nguyễn Văn Phong

Reputation: 14208

According to @Vladimir 's answer, you need to be aware of between Deferred and Immediate Query Execution in LINQ.

From that point: .First() and Single or even you foreach, For Each loop, it called Immediate Query Execution. So that's the reason why your query increases execution time several thousand times.

Some tips which one should you use?:

Immediate Query Execution

  1. If you want to cache the results of a query.
  2. If you want to get the final result without re-executing query.

Deferred Query Execution

  1. If you want to build the complexity of a query in several steps by separating query construction from query execution.

  2. If you want to fetch the latest information.

Upvotes: 0

pil0t
pil0t

Reputation: 2185

In the first code example you are not executing query, only creating it.

First(), Single(), ToArray() and some other methods triggering query execution / enumeration.

Upvotes: 2

Related Questions