I want to know if Array.Resize deletes the old allocated Array, and if yes when?
I assumed that it deletes it as soon as the values are copied.
But my teacher says that it only does so at the end of the program, meaning that the memory could be full with the old allocated values.
Is that so?
The old Array is not used in my code after the resize, this should call the GC, shouldn't it?
When objects are garbage-collected is a nondeterministic process and you shouldn’t care for that too much.
However what is deterministic is when the array is eligible for GC. This is when it gets out of scope, or more specific, when there are no more references to it. This happens for example when you’re outside the method that contains the array. Being marked for GC however won’t delete it, there needs to be some memory pressure on the GC which will make the GC clean up resources.
HimBromBeere and erikallen already explained what happens. We can also easily verify this experimentally.
Consider the following code:
static void Main(string[] args)
{
byte[] a = new byte[] { };
long total = 0;
Console.WriteLine("Iteration | curent array size (KB) | total allocations (KB) | private memory size (KB)");
for (int i = 1; i < Int32.MaxValue; i++ )
{
Array.Resize(ref a, i);
total += i;
if (i % 10000 == 0)
{
Console.WriteLine(i.ToString().PadLeft(9) +
(i / 1024).ToString().PadLeft(25) +
(total / 1024).ToString().PadLeft(25) +
(Process.GetCurrentProcess().PrivateMemorySize64 / 1024).ToString().PadLeft(27));
}
}
}
which yields the following result:
Iteration | curent array size (KB) | total allocations (KB) | private memory size (KB)
10000 9 48833 10560
20000 19 195322 10924
30000 29 439467 10976
40000 39 781269 11040
50000 48 1220727 11040
60000 58 1757841 11056
70000 68 2392612 11080
80000 78 3125039 11144
90000 87 3955122 14192
...
If all old arrays were kept im memory, we'd need around 4 GB (column total allocations) after 90000 iterations , but memory usage stays at a low 14 MB (column private memory size).
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