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.
This depends on whether the
newTypeis aclass(a reference type) or astruct(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 internallyListallocates memory in chunks, expecting to accommodate more elements.