Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List with repeat objects - What is the memory cost?

After instantiating a list (so ignoring the overhead associated with creating a list), what is the memory cost of adding the same object to a list over and over? I believe that the following is just adding the same pointer to memory to the list over and over, and therefore this list is actually not taking up a lot of memory at all. Can somebody confirm that to be the case?

List<newType> list = new List<newType>();

newType example = new newType();

for (int i = 0; i < 10000; i++)
{
   list.Add(example);
}

(Let's assume that a new newType takes up a considerable amount more of memory than a pointer does)

EDIT

newType is a class. Sorry for not clarifying that.

like image 939
carlbenson Avatar asked Jan 22 '12 02:01

carlbenson


People also ask

How much memory does a list take?

When you create a list object, the list object by itself takes 64 bytes of memory, and each item adds 8 bytes of memory to the size of the list because of references to other objects.

How objects are stored in memory in JavaScript?

In contrast, JavaScript automatically allocates memory when objects are created and frees it when they are not used anymore (garbage collection). This automaticity is a potential source of confusion: it can give developers the false impression that they don't need to worry about memory management.

How much memory is occupied by a class?

Simply a class without an object requires no space allocated to it. The space is allocated when the class is instantiated, so 1 byte is allocated by the compiler to an object of an empty class for its unique address identification. If a class has multiple objects they can have different unique memory locations.


1 Answers

This depends on whether the newType is a class (a reference type) or a struct (a value type). Your explanation is correct for reference types, but value types are copied in their entirety, so the list will grow by the size of your value type as you add elements to the list. Also note that list growing will not be uniform with element additions, because internally List allocates memory in chunks, expecting to accommodate more elements.

like image 163
Sergey Kalinichenko Avatar answered Sep 27 '22 23:09

Sergey Kalinichenko