Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 1077987
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T21:39:23+00:00 2026-05-16T21:39:23+00:00

Why does this LINQ query (Id is a property of type long in the

  • 0

Why does this LINQ query (Id is a property of type long in the Structure object):

IList<Structure> theStructures = new List<Structure>();
public int GetChildrenSlow(Structure aStructure){
   IEnumerable<Structure> childrenQuery =
                         from structure in theStructures
                         where structure.ParentStructureId == aStructure.Id
                         select structure;
   int count = childrenQuery.Count();
   //Functionality continues...
}

Run slower than this one:

IList<Structure> theStructures = new List<Structure>();
public int GetChildrenFast(long aStructureId){
   IEnumerable<Structure> childrenQuery =
                         from structure in theStructures
                         where structure.ParentStructureId == aStructureId
                         select structure;
   int count = childrenQuery.Count();
   //Functionality continues...
}

I am making this call thousands of time (recursively) and using the property is much slower than using the long directly. If I pull the Id out and store it in a long variable before I execute the LINQ command the speed is pretty much equivalent to the speed of GetChildrenFast. Why is using an object property in LINQ slower than using a primitive?

Working Example:

namespace ConsoleApplication1
{
   class Structure
   {
      public int Id
      {
         get; set;
      }

      public int ParentStructureId
      {
         get; set;
      }
   }

   class Program
   {
      private IList<Structure> theStructures = new List<Structure>();
      public Structure FirstStructure
      {
         get; set;
      }

      private int FastCountStructureChildren(long aStructureId)
      {
         IEnumerable<Structure> childrenQuery =
                         from structure in theStructures
                         where structure.ParentStructureId == aStructureId
                         select structure;

         int count = childrenQuery.Count();
         foreach(Structure childStructure in childrenQuery)
         {
            count += FastCountStructureChildren(childStructure.Id);
         }
         return count;
      }

      private int SlowCountStructureChildren(Structure aStructure)
      {
         IEnumerable<Structure> childrenQuery =
                         from structure in theStructures
                         where structure.ParentStructureId == aStructure.Id
                         select structure;

         int count = childrenQuery.Count();
         foreach(Structure childStructure in childrenQuery)
         {
            count += SlowCountStructureChildren(childStructure);
         }
         return count;
      }

      public void BuildStructure()
      {
         FirstStructure = new Structure{Id = 0, ParentStructureId = -1};
         theStructures.Add(FirstStructure);
         //The loop only goes to 6000 as any more than that causes
         //a StackOverflowException my development machine.
         for(int i=1; i<6000; i++)
         {
            Structure newStructure = new Structure{Id = i,ParentStructureId = i - 1};
            theStructures.Add(newStructure);
         }
      }

      static void Main(string[] args)
      {
         Program program = new Program();
         program.BuildStructure();

         Stopwatch fastStopwatch = new Stopwatch();
         fastStopwatch.Start();
         program.FastCountStructureChildren(0);
         fastStopwatch.Stop();

         Stopwatch slowStopwatch = new Stopwatch();
         slowStopwatch.Start();
         program.SlowCountStructureChildren(program.FirstStructure);
         slowStopwatch.Stop();

         Console.WriteLine("Fast time: " + fastStopwatch.Elapsed);
         Console.WriteLine("Slow time: " + slowStopwatch.Elapsed);
         Console.ReadLine();
      }
   }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T21:39:24+00:00Added an answer on May 16, 2026 at 9:39 pm

    Running your full example as you provided

    Fast time: 00:00:01.6187793
    Slow time: 00:00:01.3977344
    

    Only if I run in debug mode is the slow time actually slower. That is because in debug mode methods are never inlined, and there are NOPs littered everywhere to allow you to break, e.g. inside the Id getter.


    Since you obviously care about run speed, I’ll point out an unrelated inefficiency: you’re running the query twice: once for count and once for iterating over the children. Running it only once (and increasing count by 1 in the loop) should speed things up.


    The way I’d usually solve this problem, by the way, is if it ever makes sense to call the GetChildren method directly with an id, provide two overloads. Otherwise, provide the one (Structure) overload and get the id before the query, as in long id = aStructure.id;.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Does this code cause a memory leak: int main(){ int * a = new
When you log LINQ-to-SQL's query output via the Log property on the DataContext object,
I have this linq query: private void GetReceivedInvoiceTasks(User user, List<Task> tasks) { var areaIds
I have a object model a bit like this: public class Foo { public
Consider this typical disconnected scenario: load a Customer object from SQL Server using LINQ
i have tableA and tableB tableA has a B_Id property. This query works fine:
I've this Linq query: var query = (from i in session.Query<Photo>() where i.IsApproved ==
I'm constantly running up against this when writing queries with LINQ-to-XML: the Value property
I've a linq query over two Entities like this IQueryable<Employee> employees = CreateObjectSet<Employee>().AsQueryable(); IQueryable<Department>
I have this LINQ query var Cities= (from city in AllCities where (city.NumberOfCitizens >

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.