反复呼唤 - 编码实践

rel*_*xxx 11 c++ performance

你更倾向哪个?(当然getSize不做任何复杂的计数,只返回成员值)

void method1(Object & o)
{
    int size = o.getSize();

    someAction(size);
    someOtherAction(size);
}
Run Code Online (Sandbox Code Playgroud)

要么

void method2(Object & o)
{
    someAction(o.getSize());
    someOtherAction(o.getSize());
}
Run Code Online (Sandbox Code Playgroud)

我知道我可以测量哪一个更快但我想要一些评论......不只是执行时间相关...例如.如果你更喜欢method2,你最多使用o.getSize多少次,你使用method1方式的数字是多少?任何最佳做法?(想象甚至不同类型然后int)TY

Aln*_*tak 10

我会选择方法1,不仅因为它可能稍微快一点,而且主要是因为这意味着我不必担心被调用的方法是否有任何副作用.

此外,如果在多线程程序中调用它,这可以确保我总是使用的大小值 - 否则它可能在两次调用之间发生了变化.当然,在某些情况下,您可能明确地想要注意到该更改,在这种情况下使用方法2.

(是的,每其他的答案,让size一个const int保证,如果它是通过引用传递到别的东西,它不是修改).


Joh*_*web 9

由于您不希望size在调用时更改someAction()someOtherAction()(因为它不是函数的返回值时),请考虑:

void method3(const Object& o)
{
    const int size = o.getSize();

    someAction(size);
    someOtherAction(size);
}
Run Code Online (Sandbox Code Playgroud)

getSize()可能很简单,或者可能正在进行昂贵的计算.此外,osomeAction()和/ 的调用之间的另一个线程可能会更改大小someOtherAction().