0

In C#, Internally List encapsulate Array.In both data structure we can access the element using index. List<T> equals Array[T] and support adding/removing items.

If the capacity of the list is full then, internally new array with size equals to 2 * capacity will be created and all element are moved to new array. Is this true?

If true,then size of the array and list are increased dynamically. What are the benefits of using List<T> over Array[T] with Array.Resize(ref myArray, 2*size);?

Aman kc
  • 17
  • 2
  • 1
    Do you mean "what is the benefit of using `List` rather than building my own implementation of `List`?" Time. – Ant P May 16 '15 at 20:54
  • Depends on the workload. List can never be faster than a manual implementation. – usr May 16 '15 at 20:54
  • 1
    This question is bordering on unclear or too broad. Yes, it is true that when you fill up the internal array kept by the list a new one with bigger size is created. I don't think it is documented that it will be twice the size though, but perhaps. Other than that, the benefit of the list is that it can grow, as such since you already know this, can you clarify what exactly you're looking for in an answer here? – Lasse V. Karlsen May 16 '15 at 20:55
  • @LasseV.Karlsen I don't think there is an official spec, but microsoft reference implementation behaves like that. – luk32 May 16 '15 at 20:58
  • Time to link to the obligatory Eric Lippert blog on performance... http://ericlippert.com/2012/12/17/performance-rant/ – DavidG May 16 '15 at 20:59
  • By the way, the question does not make sense, because they are semantically different, so performance comparison does not make sense. – luk32 May 16 '15 at 21:02

1 Answers1

0

There are a lot of variables here, a good rule of thumb would be, if the array will remain at its current size for a long period of time an Array may be more appropriate. However, in most scenarios, where the collection is transient, a list will perform better since an array has to find contiguous space in memory for its creation. I would say though the best approach with any sort of performance optimization is to measure and optimize where you actually find an issue. Premature optimization is often a waste of time.

Gent
  • 2,555
  • 1
  • 22
  • 32