119

What is the difference between the AddRange and Concat functions on a generic List? Is one recommended over the other?

LosManos
  • 7,195
  • 6
  • 56
  • 107
johnc
  • 39,385
  • 37
  • 101
  • 139

3 Answers3

145

They have totally different semantics.

AddRange modifies the list by adding the other items to it.

Concat returns a new sequence containing the list and the other items, without modifying the list.

Choose whichever one has the semantics you want.

Greg Beech
  • 133,383
  • 43
  • 204
  • 250
  • 2
    So ion a tight loop, it would be much better to use add range so not as to lose performance due to all the internal newing and pounding the GC? – johnc Sep 19 '08 at 07:22
  • @GregBeech I know this is a very old comment, you are wrong. First of all, deferred execution has nothing to do with performance. Second of all, you mixed the two (even though you said it correctly in the actual reply). Concat creates a new object in memory without modifying the other two sequences, which is why it is slower than AddRange. When dealing with small sequences, the difference is not noticeable, but when dealing with large collections, AddRange must be used as it is significantly faster (unless you need to keep the two sequences unmodified for some reason). – Emre Bener Jun 05 '23 at 11:28
  • @johnc you are correct, AddRange is faster because it does not create a whole new object, however, the speed difference is negligible when dealing with small sequences. – Emre Bener Jun 05 '23 at 11:32
47

The big difference is that AddRange mutates that list against which it is called whereas Concat creates a new List. Hence they have different uses.

Also Concat is an extension method that applies to any IEnumerable<T> and returns an IEnumerable<T> you need a .ToList() to result in a new List.

If you want to extend the content of an existing list use AddRange.

If you are creating a new list from two IEnumerable<T> sources then use Concat with .ToList. This has the quality that it does not mutate either of sources.

If you only ever need to enumerate the contents of two Lists (or any other IEnumerable) then simply use Concat each time, this has the advantage of not actually allocating new memory to hold the unified list.

CarenRose
  • 1,266
  • 1
  • 12
  • 24
AnthonyWJones
  • 187,081
  • 35
  • 232
  • 306
11

I found this interesting article talking about the difference between these 2 structures and comparing their performance...

The main idea is that AddRange is way much faster when its about big size collections.

Here is the Link

Hope this helps,

Haithem KAROUI
  • 1,533
  • 4
  • 18
  • 39
  • 4
    I've done a test comparing `Concat` and `AddRange` with a `List>` with 1000 elements, concatenated/added 100 times, and `AddRange` was extremely faster. The results were these: `AddRange` 13 ms, `Concat().ToList()` 16,000 ms, and `Concat` on an `IEnumerable` doing only the `ToList` at the end: 2,700 ms. – Andrew Jun 06 '20 at 00:23