Memory required to create instances of a Class

S

Saber

Public Class User
Private _id, _P, _L, _R As Integer
Private _balance As Int64
Private _name, _family, _tel1, _tel2, _mobile, _city, _accountNumber As
String
Private _password, _email, _ficheNumber, _postalAddress As String
Private _province, _bank As String
Private _isSpecial, _photo As Boolean
Public stk As New Stack

..
..
Properties and Functions
..
..
..
End Class

How can I calculate how much memory I need to create an instance of such
class?
Is it the sum of bits required for variables? 32+32+32+32+64+...
What about Strings and Stack?

TIA
 
D

David Browne

Saber said:
Public Class User
Private _id, _P, _L, _R As Integer
Private _balance As Int64
Private _name, _family, _tel1, _tel2, _mobile, _city, _accountNumber As
String
Private _password, _email, _ficheNumber, _postalAddress As String
Private _province, _bank As String
Private _isSpecial, _photo As Boolean
Public stk As New Stack

.
.
Properties and Functions
.
.
.
End Class

How can I calculate how much memory I need to create an instance of such
class?
Is it the sum of bits required for variables? 32+32+32+32+64+...
Value Types (Integer, Int64, Boolean) have known sizes.
What about Strings and Stack?
They are IntPtr-sized pointers to heap locations. And there is no mechanism
to determine exactly how much space they take on the heap because there's
nothing you could usefully do with this information.

Take "stk as New Stack". stk references a heap location; at that heap
location is a Stack instance. A Stack is a mix of integral fields and
pointers to objects which a are a mix of fields and pointers, etc. Moreover
multiple Use instances can share the same _name, _tel1, or stk. So even if
you could determine the size of reference types, you have to subtract out
shared instances when adding sizes together.

That being said, it's sometimes still important to have an approximation of
the memory allocation size for performance analysis. You can get an
estimate of the size by recursing the object graph and adding field sizes,
excluding reference types which are shared among instances.

Field Type - approximate size
--------------------------------
IntPtr - 4 bytes on 32bit, 8 bytes on 64bit
Integer - 4 bytes
Char - 2 bytes
String ~ IntPtr + sizeof(Integer) + sizeof(char) * length + C (but literal
strings are "interned" and shared among instances)
Stack ~ IntPtr + 2*sizeof(Integer) + sizeof(IntPtr) * length * 1.2 + C

David
 
Top