C ++性能:通过引用传递对象vs函数

问题描述 投票:-3回答:2

这是我日常工作中的一段代码。

这是课程价格:

// In class Price.hpp
private:
bool value = false;
// others
std::vector<int> vec;
...

public:
getBoolValue() { return value; }
setBoolValue( bool iValue ) { value = iValue };

// a lot of setters & getters for the others
...

这是Compute.hpp

// In class Compute.hpp
// First proposition
void computeAmount ( const Price & iPrice )

// Second proposition
void computeAmount ( const bool iValue )

这是Compute.cpp

// First proposition
void Compute::computeAmount ( const Price & iPrice ) {
    if ( iPrice.getBoolValue() ) {
      // do something
    }
}

// Second proposition
void Compute::computeAmount ( const bool iValue ) {
    if ( iValue  ) {
      // do something
    }
}

在main.cpp中,如果我们通过这种方式调用这两个不同的函数:

Compute aCompute;
Price aPrice;
// Do a lot of set for those two
....

// Discussion
aCompute.computeAmount ( aPrice );

aCompute.computeAmount ( aPrice.getBoolValue() );

价格是一个非常大的对象。因此,如果我们谈论性能(通过引用大对象传递vs传递其成员函数的返回值)您认为哪一个更有效?我会说这是相同的,并且在性能方面没有区别。

c++ performance reference
2个回答
1
投票

在效率方面,如果你传递对象aPrice本身,它将作为地址传递到内存中。所以在Compute.cpp中,当你使用iPrice时,它基本上调用aPrice及其函数,因此,它提供了与引用相同的功能。

因此,两种方法中的差异可以忽略不计。


0
投票

这似乎是一个XY问题,因为它似乎更像是一个类设计的问题

如果计算仅对Price有意义,则计算应该是Price类的一部分,即

Price::computeAmount();  // reference ivalue directly

或者它具有普遍价值,在这种情况下,将它放入Compute类是有道理的:

Compute::computeAmount(bool ivalue);  // use ivalue as a param

Price传递给另一个类只是为了取出它的一个成员似乎没有意义

性能似乎不是问题,因为大多数编译器将等同于两者(如果包含上面的成员函数,则为三个)

© www.soinside.com 2019 - 2024. All rights reserved.