简体   繁体   中英

C++: Most efficient and concise way to access a heavy member variable in a large dataset

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM