Kai Schmidt
Kai Schmidt

Reputation: 731

Efficiency of long sequences of reference members

Lets say I have some classes like these:

class A
{
public:
    int data;
};

class B
{
public:
    A& a;
    B(A& x) : a(x) {}
};

class C
{
public:
    B& b;
    C(B& x) : b(x) {}
};

A a;
B b(a);
C c(b);

If I need some class D which needs to be able to access all of the instances of the other classes, which definition of D would be better for run time and memory usage? Is there a trade-off here?

Possibility 1:

class D
{
public:
    C& c;
    D(C& x) : c(x) {}
};
D d(c);

Access the data of class A object like this: int x = d.c.b.a.data;

Possibility 2:

class D
{
public:
    A& a;
    B& b;
    C& c;
    D(A& x, B& y, C& z) : a(x), b(y), c(z) {}
};
D d(a,b,c);

Access the data of class A object like this: int x = d.a.data;

For my purposes, D2 will never be initialized with references that C does not also have access to.

Is one of these options always better than the other? Is it a time vs. space issue?

Upvotes: 0

Views: 45

Answers (1)

Michael Albers
Michael Albers

Reputation: 3779

In terms of space, it will be fairly close (unless you are allocating enormous numbers of objects). A reference is really just a pointer, so these classes aren't too big to begin with. With the second implementation of D you will get some duplication (you'll have two references to an A), but that seems like it would be negligible overall.

Time could become an issue. Using version 1 of D involves reading 5 memory locations to reach a's data member. This can potentially cause cache misses and, worst case, page faults. It seems unlikely this is would be the case. It really depends on where the objects are allocated. Not only that, but it just involves more instructions to execute d.c.b.a.data. That isn't to say that version 2 is immune to the cache/paging problems, they just get a little less likely when you are referencing fewer variables. It's hard to make any concrete statements about how much time it will take with the information you provided. These are just some potential issues.

Unless you are working with large programs and large data in a high performance setting, these considerations are likely to be moot. Better software design would likely be the overriding factor in selecting a design.

Lastly, version 1 of D seems like a better OO design than version 2.

Upvotes: 1

Related Questions