vtortola
vtortola

Reputation: 35915

What are the internal differences of a T[] and a List<T> in terms of memory?

I was reading an article about array vs list, and the author says that an array is worse than a list, because (among other things) an array is a list of variables, but to me a list is also a list of variables. I mean, I can still do list[3] = new Item().

Actually, I have always somehow saw a List<T> like a wrapper for an array that allows me to use it easily without caring about handling its structure.

What are the internal differences between a T[] and a List<T> in terms of heap/stack memory usage?

Upvotes: 5

Views: 89

Answers (2)

nmclean
nmclean

Reputation: 7734

The author's point about a "list of variables" wasn't about memory. It's that an array contains your internal variables, and returning it allows them to be reassigned by the caller. It comes down to this:

Only pass out an array if it is wrapped up by a read-only object.

If you pass out an internal List<T>, you have the same problem, but here's the key:

We have an extensibility model for lists because lists are classes. We have no ability to make an “immutable array”. Arrays are what they are and they’re never going to change.

And, at the time the article was written, the IReadOnlyList interface didn't exist yet (.NET 4.5), though he probably would have mentioned it if it had. I believe he was advocating implementing an IList<T> that would simply throw an exception if you tried to use the setter. Of course, if the user doesn't need the ability to access elements by index, you don't need a list interface at all -- you can just wrap it in a ReadOnlyCollection<T> and return it as an IEnumerable<T>.

Upvotes: 1

Tolga Evcimen
Tolga Evcimen

Reputation: 7352

Since an array is a static structure, after the initialization, it allocates the memory that you've demanded.

int arr[5];

For example here there are 5 int objects created in memory. But when you use lists, according to its implementation, it gives you first an array with predefined capacity. And while you are adding your elements, if you exceed the capacity then it scales up. In some implementations it just doubles its size, or in some implementations it enlarges itself when the granted capacity is half full.

Upvotes: 2

Related Questions