开发者

Static variables in the scope of a draw function in OpenGL?

As an example, I have the following draw function in some OpenGL application:

void Terrain::Draw(float ox, float oy, float oz) {
    float terrainWidth = stepWidth * (width - 1.0f);
    float terrainLength = stepLength * (length - 1.0f);
    float start开发者_StackOverflow社区Width = (terrainWidth / 2.0f) - terrainWidth;
    float startLength = (terrainLength / 2.0f) - terrainLength;

        (...)
}

Terrain is a class and I'm sure that the step and terrain width/length instance variables will never change during the lifetime of the object (they are initialized before the first call to the draw function).

Assuming my application runs at a steady 25fps, the function will be called 25 times a second. The values will never change, they will always be the same.

Would I gain anything in declaring those function variables as static? To prevent them from being destroyed and declared every time the function is called?


Compilers are so good at micro optimizations these days that it would be nearly impossible to make a definitive statement on whether it would improve or slow down your program.

You will have to benchmark to really be sure.


Would I gain anything in declaring those function variables as static?

it's really a small amount of data: don't bother, unless you have a ton of instances.

To prevent them from being destroyed and declared every time the function is called?

this typically takes the form:

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;
};

then you can use the precalculated invariants from your Draw implementation.


Yes, and while you are there, make them const too. Both of these can be hints to the compiler to optimize these function variables.

Though the difference would be so mininal you'd need at least 25,000 calls per second to make this worthwhile.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜