c++optimizationstatic-variables

What are the criteria for deciding to use a static variable for optimization?


Here is an example code why I started thinking about this

void renderScene(void)
{
    //Clear all pixels
    glClear(GL_COLOR_BUFFER_BIT);
    // Question : Declaring posAttrib as a static variable is good? or bad?
    GLint posAttrib = glGetAttribLocation(programID, "vtxPosition");


    glVertexAttribPointer(posAttrib, 3, GL_FLOAT, GL_FALSE, 0, ((void*)(0)));
    glEnableVertexAttribArray(posAttrib);
    glDrawArrays(GL_POINTS, 0, 3);

    //Double buffer
    glutSwapBuffers();
}

This is about OpenGl, and renderScene() will be called whenever my screen renders. So I think if I declare posAttrib as a static variable, it will reduce unnecessary calls.

But I learned using static variable causes many problems so dont use it. I considered what would be best. So I searched about it and read those posts

Declaring variables inside loops, good practice or bad practice?

Optimization for global and static variables

static variables in functions

This post said but the initialization is likely to take place at each loop iteration. and you probably should not worry about this kind of optimization. And I've read many posts advising against using static variables.

But in other opinions,using static variables is recommended for actions that incur high memory copy costs.

I'm not sure when to use static variables based on my level of CS knowledge.

Should I measure the performance difference between using and not using static variables to make a decision? But I expect this method would be difficult to use as I collaborate with more people and the project grows larger. I want to have a basis for deciding whether or not to use it on my own when writing code that accounts for a small part of the entire project.

So my question is: What are the criteria to use a static variable for optimization?


Solution

  • A static variable access might take one or two clock cycles less than a non-static variable access. (I say 'might' because with modern pipelined CPUs in most cases it will not make any difference whatsoever.)

    Optimizations that save one or two clock cycles here and there are almost never worth making, and certainly never if in doing so you then have to worry about managing the variable, avoiding mistakenly overwriting it, etc.

    The only viable reason for making a variable static as an optimization is for the purpose of optimizing not the accessing of the variable, but the initialization of that variable. In other words, if the variable is static, then you might be able to initialize it only once, whereas if the variable is not static, then you will have to initialize it each time you want to use it.

    However, you can also achieve this with a member variable of an object that lives for as long as your program runs. So, what matters is how you use the variable, not whether the variable is static or not.