C ++:在大型数据集中访问重型成员变量的最有效和简洁的方法 [英] C++: Most efficient and concise way to access a heavy member variable in a large dataset

查看:127
本文介绍了C ++:在大型数据集中访问重型成员变量的最有效和简洁的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类如 A ,包含 LargeType 的非平凡成员变量:

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

我循环遍历一个非常大的数据集并检索一个对象 a 的类型 A 。我发现以下代码(每次迭代至少出现一次):

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

我可以理解为什么版本#1运行速度比版本#2慢:迭代,所以做更多的工作。然而,我认为版本#1是更好的处理,而不是在一个循环中多次输出 a1.GetVariable()。有没有办法重写我的类,以使版本#1和版本#2的性能可比较?

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

如你所见,我添加了一个 const GetVariable的版本;这样就可以调用 const A const A& 类型的对象上的方法。

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

这篇关于C ++:在大型数据集中访问重型成员变量的最有效和简洁的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆