耦合性能问题(一个更大的向量与更小的块向量)以及是否值得为向量的跳转访问存储迭代索引?

Couple performance questions (one bigger vector vs smaller chunks vectors) and Is it worth to store iteration index for jump access of vector?

我对向量优化有点好奇,有几个问题。 (我还是编程初学者)

示例:

struct GameInfo{
    EnumType InfoType;
    // Other info...
};

int _lastPosition;
// _gameInfoV is sorted beforehand
std::vector<GameInfo> _gameInfoV;

// The tick function is called every game frame (in "perfect" condition it's every 1.0/60 second)
void BaseClass::tick()
{
    for (unsigned int i = _lastPosition; i < _gameInfoV.size(); i++{
        auto & info = _gameInfoV[i];
        if( !info.bhasbeenAdded ){
            if( DoWeNeedNow() ){
            _lastPosition++;
            info.bhasbeenAdded = true;
            _otherPointer->DoSomething(info.InfoType);
            // Do something more with "info"....
            }
            else return;  //Break the cycle since we don't need now other "info"
        }
    }
}

_gameInfoV 矢量大小可以在 20005000 之间。

我的主要 2 个问题是:

  1. 是保持原样更好还是把它做成更小的块更好,每个不同的都会检查GameInfo.InfoType

  2. 是否值得存储向量的最后一个起始位置索引而不是从头开始迭代。

请注意,如果使用较小的向量,将会有 3 to 6

第三件事可能是我没有使用向量迭代器,但是这样使用安全吗?

std::vector<GameInfo>::iterator it = _gameInfoV.begin() + _lastPosition;
for (it = _gameInfoV.begin(); it != _gameInfoV.end(); ++it){
    //Do something
}

注意:它将用于智能手机,因此在针对较弱的手机进行优化时,我们将不胜感激。

-谢谢

  1. 不要;除非你经常移动内存
  2. 如果你做对了就不麻烦了:

    std::vector<GameInfo>::const_iterator _lastPosition(gameInfoV.begin());
    // ...
    for (std::vector<GameInfo>::iterator info=_lastPosition; it!=_gameInfoV.end(); ++info)
    {
        if (!info->bhasbeenAdded)
        {
            if (DoWeNeedNow())
            {
                ++_lastPosition;
                _otherPointer->DoSomething(info->InfoType);
                // Do something more with "info"....
            }
            else return;  //Break the cycle since we don't need now other "i
        }
    }
    

将一个向量分成几个较小的向量通常不会提高性能。它甚至可能会略微降低性能,因为编译器必须管理更多变量,这些变量会占用更多 CPU 寄存器等

我不懂游戏所以不明白GameInfo.InfoType的含义。如果您通过循环进行更多的总迭代(其中每个循环迭代执行相同类型的操作),您的处理时间和 CPU 资源需求将会增加。因此,如果分离向量会导致您避免一些循环迭代,因为您可以跳过整个向量,这将提高应用程序的性能。

迭代器是遍历容器的最安全方式。但是对于向量,我通常只使用索引运算符 [] 和我自己的索引器(一个普通的旧无符号整数)。