Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Array or List for a single Class type

Tags:

arrays

c#

list

I have a class that contains a few basic types. (3x float, 2x int).

Now I need a collection that can hold several million instances of this class. I need no derived types. All elements are exactly from this single class. Further more the number of elements is fixed. In very rarely cases I plan to copy the whole list/array and modify the copy. The originally list/array shall be immutable, thus I don't need to syncronize with other threads.

Now the question are:

  • Do I benefit from an Array instead of a List?
  • Do I save memory using an Array?
  • What about speed?

I read that a List in C# is internally implemented as Array as well.

If it would be C++, I know that the array would hold the complete object. But I'm not sure how C# handles this. Will a C# array only hold references to the class instances or will it hold the complete datastructure?

like image 869
be_mi Avatar asked Oct 22 '14 06:10

be_mi


Video Answer


1 Answers

The originally list/array shall be immutable, thus I don't need to synchronize with other threads.

Did you consider an immutable collection instead of T[] or List<T>? ImmutableArray<T> would make the most sense. You can use ImmutableArray<T>.Builder to create the collection in efficient way.

  • Do I benefit from an Array instead of a List?

If you don't need the number of elements to change you should use Array. It will make it clear to everyone who looks at your code that you're not changing the number of elements.

  • Do I save memory using an Array?

It depends how you'd create the List<T>. Internally, when you add elements to List<T> one by one underlying array's size is changes using 2* multiplier: when there is not enough space for new element current underlying array is replaced by a new one with twice the size. So yes, you can save memory using Array directly, because you won't have any unnecessary memory allocated. However, you can achieve the same using List<T>, either by creating it using constructor that takes list capacity or by calling TrimExcess method after all elements are added to the list.

  • What about speed?

Using array you'll save logic that makes List<T> methods, properties and indexer property calls translated to underlying array calls. But you shouldn't care about that, it will be unnoticeable.

If it would be C++, I know that the array would hold the complete object. But I'm not sure how C# handles this. Will a C# array only hold references to the class instances or will it hold the complete datastructure?

It depends. If you define your type as reference type (a class) both array and list would just hold a reference to particular items. If you define it as value type (a struct), array will hold the actual elements.

like image 71
MarcinJuraszek Avatar answered Sep 21 '22 10:09

MarcinJuraszek