Is there a performance difference for declaring a large variable inside a function as “static”?

Not sure if this has already been asked before. Answering this very simple question , I asked myself instead. Consider this:

void foo()
{
    int i{};
    const ReallyAnyType[] data = { item1, item2, item3,
        /* many items that may be potentially heavy to recreate, e.g. of class type */ };
    /* function code here... */
}

Now, theoretically, local variables are recreated every time control reaches a function, right? That is, look at the int iabove - it will be recreated on the stack for sure. What about the array above? Can the compiler be as smart as to optimize its creation only once, or do I need a modifier statichere? But what if the array is not const? (OK, if this is not constpossible, I have a point in creating it only once, since between calls due to modifications made during the execution of the function, it may be necessary to reinitialize to the default state.)

It may sound like a basic question, but for some reason I'm still pondering. Also, ignore “why do you want to do this” - this is a language issue that does not apply to a particular programming problem or design. I mean both C and C ++. If there are differences between the two questions on this issue, describe them.

+4
source share
2 answers

There are two questions, I think:

  • Can the compiler optimize the object static constso staticthat it can be created only once; and

  • This is a reasonable expectation that this compiler will do this.

, - "", , static. , , ( , , , :-)). , static, , .

, " ", .

, - /, / , . ( , , ++).

, .

, - , .

, - , , , - , . , , - ( ), . , . ( , , .)

, , , . , , , .

+4

, , , , , . , POD ( , POD, - / , ).

+2

Source: https://habr.com/ru/post/1627627/


All Articles