我刚刚读过this question ,这给我提出了另一个问题:
考虑这个类:
class Foo
{
public:
void setA(int a) { m_a = a; }
void setB(int b) { m_b = b; }
private:
int m_a, m_b;
};
也可以使用“流畅接口(interface)”方法编写:
class Foo
{
public:
Foo& setA(int a) { m_a = a; return *this; }
Foo& setB(int b) { m_b = b; return *this; }
private:
int m_a, m_b;
};
现在,如果我编写以下代码片段:
int main()
{
Foo foo;
foo.setA(1);
foo.setB(2);
}
如果我使用该类的第二个实现,附加的 return
指令是否会导致性能差异?
我应该打扰吗? (我的猜测是“不”)
最佳答案
Is there a performance difference induced by the additional return directives if I use the second implementation of the class?
不知道,你的编译器和优化器设置有吗?我认为没有什么可以阻止在您给出的确切情况下优化任何开销,但我可以想象为一个没有优化这种情况的深奥平台编写一个幼稚的、次优的编译器。
如果您认为这在特定情况下很重要,test it instead of assuming .
关于c++ - 定义流畅的界面会对性能产生影响吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4899992/