Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is faster: Union or Concat?

Which is faster: Union or Concat?

I don't care about the order of the elements.

Enumerable.Union Method

Enumerable.Concat Method

like image 784
Jader Dias Avatar asked Aug 26 '09 21:08

Jader Dias


3 Answers

Do you only care about execution speed? How long does it take you to process an element when you receive it?

Concat is simpler - it doesn't need to perform any processing itself, or buffer the results that it's already returned. However, it will produce more results if there are any elements in the intersection. If you're going to take a long time to process each result, Concat may end up effectively being slower.

like image 33
Jon Skeet Avatar answered Oct 08 '22 13:10

Jon Skeet


Union removes duplicates. Concat does not.

So, they produce different results if the sources either contain any items in common, or have any internal duplicates.

If you can guarantee there are no duplicates, or if there are few and you don't care about having them in your output, Concat will be faster since there's no need to test each value against what has already been yielded.

However, if there are many duplicates and you don't need them, the extra processing in Union to remove the dupes may be offset by the savings in your code that consumes the results.

like image 105
richardtallent Avatar answered Oct 08 '22 12:10

richardtallent


What was said above is right. Here is just a little addition for some special cases:

If you have to concatenate for example two lists and if you need full speed, consider using yield. Of course this is a lot less flexible and comfortable than Union or Concat in Linq. Therefore it makes only sense in special cases.

This property for example will provide the same as List1.Concat(List2)

public IEnumerable<MyObject> AllObjects
{
    get
    {
        foreach (MyObject o1 in List1)
            yield return o1;

        foreach (MyObject o2 in List2)
            yield return o2;
    }
}
like image 3
Knasterbax Avatar answered Oct 08 '22 11:10

Knasterbax