0

Is there a difference in memory usage / allocation for the class myObjectA and myObjectB?

For example if I don't want to add a velocity to every object of that class will is use more memory having new float[2] in the class?

Also whats the memory usage of "itemA" if I create a new "myObjectA" object but I don't add a new ItemA aka its at null, does it still use memory?

and how much memory would it use if I create an new "ItemA" (myItem) and then create a new "myObjectA" (myObject), myObject.item = myItem;I assume it' a pointer pointing at (myItem)as reference but how much memory would that pointer use? and is there a difference between leaving it at null?

Example C#

    public class itemA
    {
        Color color = Color.FromArgb(255,0,0); //3byte 
    }
    itemA myItem = new itemA();

    public class myObjectA
    {
        float[] pos; // ?byte
        float[] velocity; // ?byte
        itemA item; // ?byte
    }
    myObjectA myObject0 = new myObjectA();

    public class myObjectB
    {
        float[] pos = new float[2]; // 8byte
        float[] velocity = new float[2];// 8byte
        itemA item; //?byte
    }
    myObjectB myObject1 = new myObjectB();
Patrik Fröhler
  • 1,221
  • 1
  • 11
  • 38

1 Answers1

2

There is a difference in memory usage between the two classes at the time creation. As you point out, myObjectA will have unassigned variables, while myObjectB will assign arrays to these variables.

As soon as you assign objects to the variables in myObjectA, the pointers will be set to those objects, and the memory use will be determined by how large these arrays are. Assuming that you intend to create them exactly as in myObjectB - as float[2], then myObjectA and myObjectB will use the same amount of memory.

As for the size of an unassigned variable, while the pointer will not point to an object in memory, the pointer itself will still exist, and will have the default pointer size for your OS.

See How big is an object reference in .NET? for pointer sizes.

For the final question, it depends. What are you trying to accomplish by making this class generic? I would suggest asking a separate question for this.

bic
  • 867
  • 1
  • 8
  • 21