A good way to estimate / calculate the size of an object in memory

Suppose I have a Tom object that has a Person class.

Class Person String Name DateTime BirthDate String Role Int32 Salary 

Can you give me an approximate size of his memory if he has the following meanings:

Name = Tom. Date of birth = 1/1/1990. Role = User. Salary = 30000

Could you also tell us how the calculation was performed?

+1
source share
1 answer

To get the true number, use the CLR profiler . To do this programmatically, use sizeof (only works with value types). You can also do this by specifying GC directly like this ...

 long StopBytes = 0; foo myFoo; long StartBytes = System.GC.GetTotalMemory(true); myFoo = new foo(); StopBytes = System.GC.GetTotalMemory(true); GC.KeepAlive(myFoo); // This ensure a reference to object keeps object in memory long TotalBytes = StopBytes - StartBytes; MessageBox.Show("Size is " + TotalBytes.ToString()); 
+2
source

Source: https://habr.com/ru/post/1380391/


All Articles