Reputation: 1204
I have a class such as A
that contains a non-trivial member variable of type LargeType
:
class A {
public:
LargeType SetVariable(LargeType var){_var = var;}
LargeType GetVariable(){return _var;}
private:
LargeType _var;
};
I loop through a very large dataset and retrieve an object a
of type A
in every iteration. I have found that the following code (which occurs at least once per iteration):
//---- Version#1
LargeType var = a.GetVariable();
if(anotherLargeType == var){ DoSomething();}
DoOperation(var);
runs slower than the following code:
//---- Version#2
if(anotherLargeType == a1.GetVariable();){ DoSomething();}
DoOperation(a1.GetVariable());
I can appreciate why Version#1 runs slower than Version#2: a copy constructor is called in every iteration, so more work is done. However, I would argue that Version#1 is nicer to deal with, rather than having to type out a1.GetVariable()
multiple times in one loop. Is there a way to rewrite my class so that the performance of Version#1 and Version#2 are comparable?
Upvotes: 0
Views: 114
Reputation: 12757
You should return a reference to your member variable. Doing so, you don't waste time creating and/or copying temporaries:
class A {
public:
void SetVariable(const LargeType& var){_var = var;}
LargeType& GetVariable(){return _var;}
const LargeType& GetVariable() const {return _var;}
private:
LargeType _var;
};
As you can see, I added a const
version of GetVariable
; that's to make it possible to call the method on objects of type const A
and const A&
.
To avoid creating unwanted copies, you must use references in the calling code too:
//---- Version#1
LargeType& var = a.GetVariable();
if(anotherLargeType == var){ DoSomething();}
DoOperation(var);
Upvotes: 7