Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
190 views
in Technique[技术] by (71.8m points)

performance - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...