Why GC.GetTotalMemory returns different results?
When I try this code
public static void Main()
{
Console.WriteLine("Total bytes : " + GC.GetTo开发者_C百科talMemory(true));
Console.WriteLine("Total bytes : " + GC.GetTotalMemory(true));
Console.WriteLine("Total bytes : " + GC.GetTotalMemory(true));
Console.ReadKey();
}
I get these results
Why there is a difference between first and rest of the results?
One reason for this would be that your code is translated to something like this:
int totalMemory = GC.GetTotalMemory(true);
string s = "Total bytes : " + totalMemory;
Console.WriteLine(s);
On the second line of the above code, the String
class is initialized, if it hasn't been already. That means its static fields are initialized and its static constructor is called (if it has any). Then the Concat()
method is called, and all classes required during its run are initialized too.
And on the third line the Console
class is initialized, if it hasn't been already. Then of course all the classes used during the execution of WriteLine()
too.
All the static fields require some memory, so it males sense that when you call GC.GetTotalMemory()
for the second time, you get a somewhat higher number.
Not sure, but Console.WriteLine
is consuming memory... That's becaues after one call to it memory value doesn't change.
Have look to this answer help you to find out the thing in more detail : High memory usage with Console.WriteLine()
精彩评论