Wednesday 3 June 2009

Linq Performance

Something to think carefully when using Linq is performance of certain extensions.

If you have a large in memory collection that you wish to find an element in and you know that there is only one, your first instinct maybe to use the Single operator. Now, unless you explicitly want to check that there is only one item that matches your predicate, then you will incur the overhead of always searching the entire list. But, if you know that there is only one item that should match your predicate and ensuring this isn't called for, then First should be the operator of choice as this will stop searching as soon as it finds the item that matches the predicate.

Now, whilst this might seem like a small saving, it is saving that doesn't take much thought to implement.

Submit this story to DotNetKicks Shout it

2 comments:

  1. I seem to remember someone asking me to change .First for .Single but I just can't remember who ... :-)

    ReplyDelete
  2. In certain areas I would say to use Single when you want to be test that there is only one instance of an item matching the predicate. I believe that the person who asked you to make this change probably knew that the collection being considered couldn't be relied on to only have one instance in the collection.
    In the code that inspired this post, I had unit tested the code to death and was always in control of the collection, i.e., it didn't come from an outside source and so there was only performance penalties to incur from using .Single.
    The more I think about it the more this person sounds wise!

    ReplyDelete