Caerulius
Caerulius

Reputation: 425

Performance regarding storing entire objects as parameters to other objects

I have a system where Object A can at will produce Object B. One Object A can produce any number of Object B, and there are multiple Object A's.

It is useful in my program to know WHICH Object A produced which Object B (for various reasons). Currently, whenever an Object B is created, I just store the Object A that created it as a parameter inside Object B. But this doesn't feel right to me.

Question 1: Is there a way to store simply a reference to the correct Object A inside the Object B, instead of the whole object? Or is that actually what's happening anyways?

Question 2: Is doing it the way I am now inefficient for memory?

Upvotes: 1

Views: 54

Answers (3)

mipe34
mipe34

Reputation: 5666

Question 1:

Yes it is possible. You can pass a reference to creator object e.g. by constructor. It could be also by public property setter or public field but I would recommend to use constructor.

public class ObjectB
{
    public ObjectA Parent {get; private set;}

    public ObjectB(ObjectA parent)
    {
        this.Parent = parent;
    }
}

public class ObjectA
{
    private ObjectB GetNewObjectB()
    {
         return new ObjectB(this);
    }
}

Question 2:

Object reference takes 4bytes/8bytes on 32bit/64bit OS. So you can roughly imagine the additional memory consumption and determine, if it is an issue for you (IMHO it would not be an issue for most of the applications).

Upvotes: 2

Lee
Lee

Reputation: 144136

Classes are reference types, so if your class B has a field of type class A then only a reference to the instance of A is stored in the field, not a copy of the entire object.

class B
{
    //creator is a reference to the instance of A which created this instance
    private A creator;
}

Upvotes: 0

G-Man
G-Man

Reputation: 103

Question 1: Yes - if you have

class A {}

class B
{
  A creator;
}

then the 'creator' reference is just that - a pointer to the object instance rather than a copy of the content itself.

Question 2: I don't think I have enough information to answer this - if you need the reference stored in B then its not inefficient. You might want to turn it into a WeakReference if you are happy for it to become invalid.

Upvotes: 0

Related Questions