← Back to Index

#optimization 比如有如下代码

void PucchAllocationInfo::xsfnNotValidLogWarning(
    const PucchInfo& pucchInfo,
    const utils::Xsfn& xsfn,
    const itf::Rnti rnti) const
{
    const auto& pucchInfoXsfn = pucchInfo.xsfn();
    if (pucchInfoXsfn != xsfn and pucchInfoXsfn.isValid())
    {
        LG_WRN(
            "PucchAllocationInfo get pucchInfo error, rnti(%u)saved xsfn(%d,%d), input(%d,%d) xsfn exceed "
            "maxHarqAckWaitingWindow.",
            rnti,
            pucchInfoXsfn.sfn(),
            pucchInfoXsfn.slot(),
            xsfn.sfn(),
            xsfn.slot());
    }
}

在这份代码中,我们通过pucchInfoXsfn把pucchInfo.xsfn()通过引用的方式记录下来,后继多次再进行这个变量的访问。相关的汇编代码如下

image.png

如果代码进行下面的改动

void PucchAllocationInfo::xsfnNotValidLogWarning(
    const PucchInfo& pucchInfo,
    const utils::Xsfn& xsfn,
    const itf::Rnti rnti) const
{
    if (pucchInfo.xsfn() != xsfn and pucchInfo.xsfn().isValid())//remove pucchInfoXsfn, use pucchInfo directly.
    {
        LG_WRN(
            "PucchAllocationInfo get pucchInfo error, rnti(%u)saved xsfn(%d,%d), input(%d,%d) xsfn exceed "
            "maxHarqAckWaitingWindow.",
            rnti,
            pucchInfo.xsfn().sfn(),
            pucchInfo.xsfn().slot(),
            xsfn.sfn(),
            xsfn.slot());
    }
}

再看对应的汇编代码 image.png

显然,下面的代码if判断中多了一次pucchInfo.xsfn()的访问。但实际上,第二份代码xsfnNotValidLogWarning函数的指令数是减少的。

我们得到了下面的结论: 1. 变量命名不一定会提高效率,这得结合具体的业务逻辑来判断。在上面的代码中,创建引用变量花了4个IR, 调用次数 7485次,那么总共需要花费 29940个指令。但实际上代码走到isValid()的次数为584次,也就是说其中有(7458-584) * 4=27496 个是额外的调用(只有在两次xsfn调用,那额外的变量定义才有意义)。再看xsfn的调用花费了5个指令,对于下面的代码我们需要额外小号 584 * 5 = 2920 个指令。两相比较(27496 VS 2920),还是第二份代码更高效! 2. alias 变量可以提高效率。从上面的例子中我们也能看出,编译器并不会对同一个类型下的成员多次访问进行优化。 3. 应根据具体的业务逻辑来进行判断