Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 895
vtortola Avatar asked Oct 20 '22 19:10

vtortola


1 Answers

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.

like image 178
Tolga Evcimen Avatar answered Oct 24 '22 00:10

Tolga Evcimen