Can someone please tell me whether AddB below will result in less CLR allocations than AddA? I’ve examined disassembly and it looks to be the case but I’d like confirmation from the Experts please. Can someone Exchange this information with me please?
Cheers,
Charlie.
namespace A
{
struct Vec2
{
public float x;
public float y;
public Vec2 AddA(Vec2 other)
{
Vec2 v = new Vec2(); // Reference variable
v.x = x + other.x;
v.y = y + other.y;
return v;
}
public Vec2 AddB(Vec2 other)
{
Vec2 v; // Value variable
v.x = x + other.x;
v.y = y + other.y;
return v;
}
}
}
If Vec2 is a
structin both examples, by usingVec2 v = new Vec2();you are not creating a reference to your struct, you are simply creating a new struct on your stack. If you don’t use thenewkeyword, your struct is nevertheless created on the stack and you can initialize each field separately.In that case, using the
newkeyword for a struct does’t make much sense if your constructor doesn’t accept some meaningful parameters to initialize the data in a single line.If the first method uses a
classinstead of astruct, then it does create an object for GC to collect, unlike the second method. Since v inAddBis allocated on the stack, it is not collected, the stack is simply popped when your method is finished.