几对性能问题(一个较大的向量与较小的块向量),值得存储迭代索引以进行矢量访问

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

本文关键字:向量 访问 迭代 存储 值得 索引 问题 性能 一个      更新时间:2023-10-16

我对矢量优化有些奇怪,并有几个问题。(我仍然是编程的初学者)

示例:

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之间。

我的主要两个问题是:

  1. 最好离开它的方式,或者更好地制作较小的块,这对每个不同的GameInfo.InfoType

  2. 都可以检查一下
  3. 是值得存储向量的最后一个启动位置索引而不是从一开始迭代的麻烦。

请注意,如果使用较小的向量,则会像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资源要求将会增加。因此,如果分开向量会导致您避免进行一些循环迭代,因为您可以跳过整个向量,这将提高应用程序的性能。

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