使用 SFML 的 C++ 中基于迭代器的循环和基于索引的循环之间存在显着的性能差异

问题描述 投票:0回答:0

我正在使用 C++ 中的 SFML 开发一个简单的 2D 网格可视化游戏引擎。我有一个带有 std::vector 的 Grid 类,其中网格中的每个单元格由 6 个顶点表示。当我根据每个单元格的状态更新其颜色时,我观察到两个循环之间存在巨大的性能差异:一个循环使用向量的迭代器,另一个循环使用基于索引的方法。

这就是差异所在:

inline void ChangeCellColor(Cell& cell, sf::Color color)
{
    // index-based loop
    auto index = cell.grid_y * width_ + cell.grid_x;
    for (int i = 0; i < 6; ++i)
    {
        vertices_[index * 6 + i].color = color;
    }

    // iterator-based loop (commented out for now)
    /*
    auto index = cell.grid_y * width_ + cell.grid_x;
    for (auto it = vertices_.begin() + index * 6; it != vertices_.begin() + index * 6 + 6; ++it)
    {
        it->color = color;
    }
    */
}

使用基于索引的循环,我实现了 1150-1350 范围内的 FPS。然而,当我切换到基于迭代器的循环时,FPS 急剧下降到 30-45。

两种方法之间如此巨大的性能差异背后的原因可能是什么?我是否遗漏了向量迭代器的一些内容?

c++ c++17 sfml stdvector
© www.soinside.com 2019 - 2024. All rights reserved.