Im using .NET 4.0 c#.
I just realised today that a performance issue was partially caused by this :
var feuilleDeTemps =
from fdt in context.FeuilleDeTemps.Include("FeuilleDeTempsJournees");
...
feuilleDeTemps.First().Property
feuilleDeTemps.First().Property
feuilleDeTemps.First().Property
feuilleDeTemps.First().Property
...
FeuilleDeTemps myFT = feuilleDeTemps.First();
return myFT;
I was using the first element of feuilleDeTemps (about 4 times per loop x 60 loops) before setting it in a normal variable like this :
FeuilleDeTemps myFT = feuilleDeTemps.First();
Then i realised it was causing a performance issue. I used this instead :
var feuilleDeTemps =
from fdt in context.FeuilleDeTemps.Include("FeuilleDeTempsJournees");
FeuilleDeTemps myFT = feuilleDeTemps.First();
...
myFT.Property
myFT.Property
myFT.Property
myFT.Property
...
return myFT;
I was using feuilleDeTemps.First().Property about 240 times.
Now im using it 60 times and the 240 uses of the property goes directly by the Typed Variable.
It made my code take 2x less time to execute (3 seconds vs 6 seconds which is still pretty slow)…
Why?
The query you stored in
feuilleDeTempsisn’t actually executed until you request a value. In your case this happens when you callFirst. Generating the query object is usually very fast. It is the execution of the query that usually takes the most time. In your example you are executing the same query multiple times, resulting in several round-trips to the database.It’s important when using LINQ to remember that there is a difference between a query, and the results of that query. In general queries are executed lazily – no data is fetched until you actually ask for it, e.g. with
First,ToList,foreach (var result in query), etc…