none
LINQ to Objects vs. data dictionary? RRS feed

  • Question

  • Is LINQ to Objects as fast and as efficient as a data dictionary? It looks like it could simplify some code I am writing, but is there a cost involved?

     

    Assume I have a data dictionary into which I have loaded Widget objects, keyed to each Widget's WidgetID property:

     

    Dictionary<int, Widget> tempCollection = new Dictionary<int, Widget>();

     

     Assume that I need to get the Widgets from the dictionary and arrange them in an object hierarchy. Each Widget has a WidgetID property and a Children collection property that holds a List<Widget>. Each Widget also has a ParentID property that contains the WidgetID of its parent.

     

    Assume I know the first object in tempList is the root object, and that I am guaranteed that an object's parent will be present in the hierarchy when that object is added to the hierarchy. So, I simply scan tempCollection , find each Widget's parent, and add the Widget to the parent's Children collection.

     

    I use a data dictionary to hold tempCollection so that I can easily get each Widget's parent. I scan the data dictionary by getting a list of its keys. This approach allows me to retrieve each parent from the data dictionary using the ParentID property value. That is much quicker than searching a list for the ParentID I want.

     

    With LINQ to Objects, it looks like I don't need to use a data dictionary. I can use a List<Widget>, and simply query the list for the parent I need as I load each Widget. That feels simpler and a bit more elegant than using a data dictionary, but I am concerned there may be a performance cost that I don't yet understand. So, before I profile both approaches, I wanted to check here and see if anyone has already looked into this.

     

    So, I guess my question comes down to this: Does a LINQ to Objects query execute as quickly as a fetch from a data dictionary, or is it as slow as searching a list, using a foreach loop? Thanks for your help.

     

    David Veeneman

    Foresight Systems

     

    Wednesday, April 2, 2008 8:45 PM

Answers

  •  

    Does a LINQ to Objects query execute as quickly as a fetch from a data dictionary, or is it as slow as searching a list, using a foreach loop?

     

    The latter... ...but fewer lines of code to write.

    Thursday, April 3, 2008 9:19 AM
    Answerer