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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With