C ++: the most efficient and concise way to access a large member variable in a large dataset

I have a class, such as one A, that contains a nontrivial member variable of the type LargeType:

class A {
public:
    LargeType SetVariable(LargeType var){_var = var;}
    LargeType GetVariable(){return _var;}
private:
    LargeType _var;
};

I go through a very large dataset and get an object of Atype Aat each iteration. I found that the following code (which happens at least once per iteration):

//---- Version#1
LargeType var = a.GetVariable();
if(anotherLargeType == var){ DoSomething();}
DoOperation(var);

works slower than the following code:

//---- Version#2
if(anotherLargeType == a1.GetVariable();){ DoSomething();}
DoOperation(a1.GetVariable());

, №1 , # 2: , . , , № 1 , , a1.GetVariable() . , # 1 # 2 ?

0
1

-. / :

class A {
public:
    void SetVariable(const LargeType& var){_var = var;}
    LargeType& GetVariable(){return _var;}
    const LargeType& GetVariable() const {return _var;}
private:
    LargeType _var;
};

, const GetVariable; const A const A&.

, :

//---- Version#1
LargeType& var = a.GetVariable();
if(anotherLargeType == var){ DoSomething();}
DoOperation(var);
+7

Source: https://habr.com/ru/post/1608693/


All Articles