-1

I heard that List<T>.AddRange(IEnumerable<T>) faster than new List<T>(IEnumerable<T>). After looking in reflector I could not tell why ad once I created a test application Indeed I saw that it is faster.

Does anyone have an idea why?

4
  • 4
    Could you paste your sample code? Their performance will differ depending on the objects you are passing in.
    – M Afifi
    May 21, 2012 at 9:41
  • 1
    "I heard that ..." - don't believe everything you hear, especially blanket statements about performance.
    – Joe
    May 21, 2012 at 9:55
  • @Joe It came from someone who knows his stuff....
    – Amit Raz
    May 21, 2012 at 10:02
  • 1
    "It came from someone who knows his stuff...." - An Appeal to Authority (en.wikipedia.org/wiki/Appeal_to_authority) isn't convincing.
    – Joe
    May 21, 2012 at 10:43

1 Answer 1

1

Sorry I can't confirm your assumption. AddRange was always slower than the constructor variant.

I made some test code for it:

a) var list = new List<T>(enumerable);

is faster than

b) var list = new List<T>(); list.AddRange(enumerable);

tested with different IEnumerables

List: new: 32ms addrange: 47ms

LinkedList: new: 58ms addrange: 99ms

HashSet: new: 56ms addrange: 98ms

Queue: new: 271ms addrange: 516ms

5
  • 1
    I'm sure that the overhead is negligible. May 21, 2012 at 9:50
  • That's not what OP has asked. Since you're passing a List<T> to the constructor, it can simply be used to be copied into the new list whereas passing an IEnumarable<T> (f.e. Enumerable.Range(1,1000000)) may require that the enumerable must be enumerated and added one by one to the new List. Apart from that i assume that the difference in your example is negligible anyway. May 21, 2012 at 9:55
  • An IEnumerable can be of all different types. That does not neglect the fact that a new operator will add additional overhead in both cases. I don't know on what fact he bases his assumption that AddRange is faster. I can't confirm that at all.
    – BlueM
    May 21, 2012 at 9:58
  • Just a guess. Maybe the constructor depends on the effort of the Count function which is fast for a list.
    – BlueM
    May 21, 2012 at 10:04
  • I acctialy got the same conclusion so I was surprized
    – Amit Raz
    May 21, 2012 at 10:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.