首页 > 解决方案 > 指向相邻内存的指针的缓存性能

问题描述

假设我有一个实际数据的 std::map 存储在连续的内存块中,我想在跳过一些元素时对其进行迭代。我有一个函数组装指向地图元素的指针向量。我的问题是: 遍历这个指针列表并跟随它们会导致频繁的缓存未命中吗? 现在让我们假设整个地图适合几个缓存行。

编辑:代码示例。代码片段编辑器不适用于我的触摸设备,但我会尝试以可读的方式格式化。

int main() 
{
    std::map<unsigned int, MyStruct> map;
    //Fill this map with useful data.

    std::vector<MyStruct*> ptrvec; //vector of pointers to pass around. Will not be processed right here, that's just to simplify the example code

    for(MyStruct i : map)
    {
        if(/*some condition to select structs*/) 
        {
            ptrvec.push_back(&i);
        }
    }

    for(MyStruct* i : ptrvec)
    {
        //Do some processing on MyStruct
    }
}

标签: c++pointersmemory-managementiteration

解决方案


推荐阅读