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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…