重构此代码以进行优化

时间:2018-06-20 01:20:20

标签: c++ memory refactoring

bool FunctionA (const ObjectA& a)
{
    // ... some code ...
    const ObcjectB& b = getObjectBFromSomewhere(...);
    // ... code heavily reliant on b ...
    return boolean_val;
}

bool FunctionB (const ObjectA& a)
{
    bool boolean_val = FunctionA(a);

    // ... some code ...
    const ObcjectB& b = getObjectBFromSomewhere(...);
    // ... code that only needs one tiny bit of b ...
    return boolean_val;
}

FunctionA仅被调用一次。 FunctionB也仅被调用一次。两者都以不同的流程被调用。

“ getObjectBFromSomewhere”的代码占用大量内存,因此我只想调用一次。

重构此代码的最佳方法是什么?

2 个答案:

答案 0 :(得分:0)

感谢您的想法,这就是我解决问题的方法:

bool FunctionA (const ObjectA& a, bool& bSomeLittleBit = false)
{
    // ... some code ...
    const ObcjectB& b = getObjectBFromSomewhere(...);
    bSomeLittleBit = b.getSomeLittleBit();
    // ... code heavily reliant on b ...
    return boolean_val;
}

bool FunctionB (const ObjectA& a)
{
    bool bSomeLittleBit = false;
    bool boolean_val = FunctionA(a, bSomeLittleBit);

    // ... rest of the code as normal ...

    return boolean_val;
}

答案 1 :(得分:0)

您的问题似乎暗示着有一个规范的objectB不会在内存中移动,但是出于某种原因,getObjectBFromSomewhere()很难在内存中使用,但始终会返回对该同一个对象的引用?

也许您正在寻找这样的东西:

//static means only available in this compilation unit
static const ObcjectB *obj = nullptr;

bool FunctionA (const ObjectA& a)
{
    // ... some code ...
    if(!obj)
       obj = &getObjectBFromSomewhere(...);
    const ObcjectB& b = *obj;
    // ... code heavily reliant on b ...
    return boolean_val;
}

bool FunctionB (const ObjectA& a)
{
    bool boolean_val = FunctionA(a);

    // ... some code ...
    if(!obj)
       obj = &getObjectBFromSomewhere(...);
    const ObcjectB& b = *obj;
    // ... code that only needs one tiny bit of b ...
    return boolean_val;
}

如果您指的是functionA由functionB调用并因此通过调用getObjectBFromSomewhere()来执行冗余工作的事实,则可以更改functionA的签名以接受指向它将使用的对象的指针,而不是通过以下方式调用getObjectFromSomewhere:本身即

FunctionA(const ObjectA& a, ObcjectB *obj = nullptr)
{
   if(!obj)
      obj = &getObjectBFromSomewhere(...);
   const ObcjectB& b = *obj;
}

,然后更改functionB以传递此参数:

FunctionB (const ObjectA& a)
{
    //move the expensive call up to the start of the method
    const ObcjectB& b = getObjectBFromSomewhere(...);
    bool boolean_val = FunctionA(a, &b);

    // ... some code ...

    // ... code that only needs one tiny bit of b ...
    return boolean_val;
}