Don’t use Single when you can use a First!

I’m writing this post because I’ve seen too many developers who use the Single method when they want to get one element of a collection and when they know that the Single will return only one element. DON’T DO THIS!!!

In this case, use the First method.

The purpose of Single method is to return only one element (like First method) and also to verify that there is only one result.

So what does it means? Look at the following code:

int tick = Environment.TickCount;
int value = Enumerable.Range(0, int.MaxValue).First(i => i == 10);

Console.WriteLine(Environment.TickCount – tick);

The console indicates 62. The First method loops 11 elements in the collection.

Now what about the same code with the Single method?

int tick = Environment.TickCount;
int value = Enumerable.Range(0, int.MaxValue).Single(i => i == 10);

Console.WriteLine(Environment.TickCount – tick);

The console indicates 28720! The method loops the 2147483648 elements of the collection to be sure that there is only one result!

qed

It’s the same with LINQ To Entities. With a First, the generated SQL query will contain a TOP 1 ; with a Single, a TOP 2. (Of course if your Single is on an indexed column, the performance impact will be near 0.

So yes the Single method (or SingleOrDefault) is useful but if and only if we want to be sure that there is only one element in the collection (and to throw an exception in this case). If it isn’t the case, don’t use it and use the First method (or FirstOrDefault).

This entry was posted in 12253, 7671, 7672. Bookmark the permalink.

One Response to Don’t use Single when you can use a First!

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>