我正在使用 C++ 中的 SFML 开发一个简单的 2D 网格可视化游戏引擎。我有一个带有 std::vector
这就是差异所在:
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。
两种方法之间如此巨大的性能差异背后的原因可能是什么?我是否遗漏了向量迭代器的一些内容?