Consider a struct like this:
struct ExampleStruct
{
public int ID;
public List<ExampleStruct> children;
}
Would the following line of code create an object on the heap?
ExampleStruct exStrct = new Examplestruct() {ID = 5, children = null};
Would the following line of code create an object on the heap?
No. Since Examplestruct
is a value type memory for it will be allocated on stack. Since you are not creating an instance of List<ExampleStruct>
(which is a reference type) there is no need to allocate memory on the heap.
null
denotes:
a literal that represents a null reference, one that does not refer to any object. null is the default value of reference-type variables
So there is nothing on the heap to point to, so no need to allocate anything there.
There are multiple ways to check this. For example by using GC.GetTotalAllocatedBytes(Boolean)
:
// "warm up"
Measure(() => new ExampleStruct() {ID = 5, children = null}, 10);
Measure(() => new ExampleStruct() {ID = 5, children = null}, 10000);
Measure(() => new ExampleStruct() {ID = 5, children = new List<ExampleStruct>()}, 10000);
static void Measure(Action action, int iterations)
{
var cur = GC.GetTotalAllocatedBytes(true);
for (int i = 0; i < iterations; i++)
{
action();
}
Console.WriteLine($"Total Allocated Bytes: {GC.GetTotalAllocatedBytes(true) - cur:N0}");
}
Which prints "on my machine":
Total Allocated Bytes: 2,008
Total Allocated Bytes: 0
Total Allocated Bytes: 320,288