1

例如,我在一些 OpenGL 应用程序中有以下绘制函数:

void Terrain::Draw(float ox, float oy, float oz) {
    float terrainWidth = stepWidth * (width - 1.0f);
    float terrainLength = stepLength * (length - 1.0f);
    float startWidth = (terrainWidth / 2.0f) - terrainWidth;
    float startLength = (terrainLength / 2.0f) - terrainLength;

        (...)
}

Terrain是一个类,我确信 step 和 terrain 宽度/长度实例变量在对象的生命周期内永远不会改变(它们在第一次调用 draw 函数之前被初始化)。

假设我的应用程序以稳定的 25fps 运行,该函数将每秒调用 25 次。价值观永远不会改变,它们永远是一样的。

将这些函数变量声明为静态变量会有所收获吗?为了防止它们在每次调用函数时被销毁和声明?

4

3 回答 3

2

如今,编译器非常擅长微优化,几乎不可能就它是否会改进或减慢您的程序做出明确的声明。

您必须进行基准测试才能真正确定。

于 2011-04-20T21:17:13.130 回答
1

是的,当你在那里的时候,也做它们const。这两者都可以提示编译器优化这些函数变量。

尽管差异如此之小,但您每秒至少需要 25,000 次调用才能使这变得有价值。

于 2011-04-20T21:16:58.430 回答
1

将这些函数变量声明为静态变量会有所收获吗?

这实际上是少量数据:不要打扰,除非您有大量实例。

为了防止它们在每次调用函数时被销毁和声明?

这通常采用以下形式:

class Terrain { 
public:
    // interface
protected:
    // more stuff
private:
    // ... existing variables
    const float d_terrainWidth;
    const float d_terrainLength;
    const float d_startWidth;
    const float d_startLength;
};

然后您可以使用实现中预先计算的不变量Draw

于 2011-04-20T21:25:29.543 回答