how much memory it will be allocated in stack as well as in heap when we instantiate the class/struct Student?
I guess id = 4 bytes reference (32 bit machine) and name = 4 bytes reference and facultyAdvisor = 4 bytes reference. So totally 12 bytes in stack and actual size will be in heap. this heap size may vary depends upon the value that we assign to the fields(id, name, facultyAdvisor) that uses object obj(Student obj = new Student())
The same is for struct also right?
public class Student { int id; string name; Professor facultyAdvisor; }
public struct Student { int id; string name; Professor facultyAdvisor; }
First note that the stack and the heap are implementation details... as is the size of the object. But in the current implementation, all the data for the fields within Student
when it's a class are on the heap. There's an object overhead as well as the memory taken for the fields, but all of that will be on the heap.
If you're keeping a reference to the new instance, and you're keeping it in an uncaptured local variable not in an iterator block or async method, that reference would be on the stack (in the current implementation) so it would be 4 bytes on a 32-bit CLR.
When Student
is a struct, things change somewhat:
Professor
is a reference type)I have a couple of articles/posts you may find useful:
EDIT: Addressing the Professor
issue, assuming Professor
is a class - unless a Professor
object is explicitly created, the reference in Student
will simply be null. Creating a new Student
does not automatically create a new Professor
just because there's a field of that type. The reference to the Professor
is just part of the data for Student
- it lives wherever the id
lives - so if Student
is a class, then the reference only exists on the heap, and if Student
is a struct then it depends on where the Student
value is created, as listed above.
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