I’ve got a PointClass and a PointStruct, both containers for storing X and Y integer values. And there’s also a PointClassFinalized with a finalizer.
The MeasureTestA method allocates an array of 1,000,000 PointClassFinalized instances.
The MeasureTestB method is almost identical, but it allocates 1,000,000 instances of PointClass instead.
And there’s MeasureTestC which allocates 1,000,000 instances of PointStruct.
Which method do you think is fastest?
Let’s find out:
Did you expect that?
Let’s focus on MeasureTestB and MeasureTestC for now. The only difference between these two methods is that the one allocates classes, and the other allocates structs.
MeasureTestC allocates structs and runs in only 17 milliseconds which is 8.6 times faster than MeasureTestB which allocates classes!
That’s quite a difference!
So what’s going on here?
The difference is caused by how structs and classes are stored in memory. Here’s what the memory layout looks like for a list of PointClass instances:
The list is a local variable, so it’s stored on the stack. It references an array of PointClass instances on the heap.
But here’s the twist: PointClass is a reference type, so it’s stored elsewhere on the heap. The list only maintains an array of object references that point to PointClass instances stored elsewhere on the heap.