Reputation: 331
I implemented a something like tree in c# in this way:
public class node {
public node parent = null;
public node leftChild = null;
public node rightChild = null;
}
Now in somewhere in the code I write below
node firstNode = new node();
firstNode.rightChild = new node();
firstNode.rightChild.parent = firstNode;
my question is how much memory this code allocates? As you see there isn't any variables like integer or double. I want to know in the structures like this which we don't use pointer How we should know about the memory allocation.We are sure this is stores in the memory but there is no exact variable to aggregate all of them and say this code allocates this amount of memory. I want to know "how much memory a reference to an instance costs" in the above code
Upvotes: 0
Views: 275
Reputation: 11577
There's nothing magic about C# references, they work in much the same way as C pointers.
Your node
object consists of three references - so allocating a new instance will take up 3 references worth of space on the heap.
The firstNode
local variable will take up the size of one reference on the stack.
An object reference is the same size as a pointer, which is normally 4 bytes on a 32-bit CPU, and 8 bytes on a 64-bit CPU. Objects on the .Net CLR also have an 8 byte overhead, so on a 32bit system, the size of a node
instance would be 8+3*4 = 20 bytes.
Upvotes: 3
Reputation: 942040
The class certainly has variables, those three node references are fields that take space in the object. Not fundamentally different from a field of type int as far as storage goes. They are pointers at runtime, 4 bytes each in 32-bit mode, 8 bytes in 64-bit mode. Since you could only worry about object size in 32-bit mode, the object will take 8 + 3 * 4 = 20 bytes. The first 8 bytes is object overhead, any object has that.
Upvotes: 1