Does static make a difference for a const local variable?What is the difference between const and...

Why do I have multiple (unassociated) temporal history tables?

Difference between `vector<int> v;` and `vector<int> v = vector<int>();`

Is there some relative to Dutch word "kijken" in German?

Is there any differences between "Gucken" and "Schauen"?

What makes the Forgotten Realms "forgotten"?

Eww, those bytes are gross

How to prevent users from executing commands through browser URL

How to explain planetary rings pulsating?

Why would the Pakistan airspace closure cancel flights not headed to Pakistan itself?

Why do neural networks need so many training examples to perform?

Strange Sign on Lab Door

How can animals be objects of ethics without being subjects as well?

Draw one function, varying color by (gradient) using another function's value

How to tag distinct options/entities without giving any an implicit priority or suggested order?

Magento 2 : Call Helper Without Using __construct in Own Module

Why exactly do action photographers need high fps burst cameras?

Injecting creativity into a cookbook

Why did other German political parties disband so fast when Hitler was appointed chancellor?

How do you funnel food off a cutting board?

Citing paywalled articles accessed via illegal web sharing

Program that converts a number to a letter of the alphabet

Why don't American passenger airlines still operate dedicated cargo flights?

Why do members of Congress in committee hearings ask witnesses the same question multiple times?

What is the purpose of easy combat scenarios that don't need resource expenditure?



Does static make a difference for a const local variable?


What is the difference between const and readonly?What are the differences between a pointer variable and a reference variable in C++?Are static class variables possible?Difference between static class and singleton pattern?What does “static” mean in C?What is the difference between const int*, const int * const, and int const *?Static variables in JavaScriptWhy are static variables considered evil?Difference between `constexpr` and `const`Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations













8















Imagine the following declaration:



void foo(){
const std::array<int, 80000> arr = {/* a lot of different values*/};
//do stuff
}


And a second one:



void foo(){
static const std::array<int, 80000> arr = {/* a lot of different values*/};
//do stuff
}


What are the possible performance differences between these two if any? And is there any danger associated with any of these solutions?










share|improve this question




















  • 3





    In the static case they may not be on the stack, but in a read-only section. Probably compiler dependent as well.

    – Matthieu Brucher
    5 hours ago






  • 3





    out of curiosity: do you have a real problem at hand, or is this just an academic exercise? (its a valid question in both cases)

    – user463035818
    5 hours ago






  • 1





    @user463035818 I am having discussion during code review ;)

    – bartop
    5 hours ago






  • 2





    depending on the reviewer that can be a real problem :P

    – user463035818
    5 hours ago






  • 4





    @Scheff withoutStatic builds the array each times it is invoked from static data (.LC0). withStatic uses an array whose construction has been optimized as a constant (withStatic()::arr).

    – YSC
    5 hours ago
















8















Imagine the following declaration:



void foo(){
const std::array<int, 80000> arr = {/* a lot of different values*/};
//do stuff
}


And a second one:



void foo(){
static const std::array<int, 80000> arr = {/* a lot of different values*/};
//do stuff
}


What are the possible performance differences between these two if any? And is there any danger associated with any of these solutions?










share|improve this question




















  • 3





    In the static case they may not be on the stack, but in a read-only section. Probably compiler dependent as well.

    – Matthieu Brucher
    5 hours ago






  • 3





    out of curiosity: do you have a real problem at hand, or is this just an academic exercise? (its a valid question in both cases)

    – user463035818
    5 hours ago






  • 1





    @user463035818 I am having discussion during code review ;)

    – bartop
    5 hours ago






  • 2





    depending on the reviewer that can be a real problem :P

    – user463035818
    5 hours ago






  • 4





    @Scheff withoutStatic builds the array each times it is invoked from static data (.LC0). withStatic uses an array whose construction has been optimized as a constant (withStatic()::arr).

    – YSC
    5 hours ago














8












8








8


2






Imagine the following declaration:



void foo(){
const std::array<int, 80000> arr = {/* a lot of different values*/};
//do stuff
}


And a second one:



void foo(){
static const std::array<int, 80000> arr = {/* a lot of different values*/};
//do stuff
}


What are the possible performance differences between these two if any? And is there any danger associated with any of these solutions?










share|improve this question
















Imagine the following declaration:



void foo(){
const std::array<int, 80000> arr = {/* a lot of different values*/};
//do stuff
}


And a second one:



void foo(){
static const std::array<int, 80000> arr = {/* a lot of different values*/};
//do stuff
}


What are the possible performance differences between these two if any? And is there any danger associated with any of these solutions?







c++ static const






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 31 mins ago









Boann

37.1k1290121




37.1k1290121










asked 6 hours ago









bartopbartop

2,967826




2,967826








  • 3





    In the static case they may not be on the stack, but in a read-only section. Probably compiler dependent as well.

    – Matthieu Brucher
    5 hours ago






  • 3





    out of curiosity: do you have a real problem at hand, or is this just an academic exercise? (its a valid question in both cases)

    – user463035818
    5 hours ago






  • 1





    @user463035818 I am having discussion during code review ;)

    – bartop
    5 hours ago






  • 2





    depending on the reviewer that can be a real problem :P

    – user463035818
    5 hours ago






  • 4





    @Scheff withoutStatic builds the array each times it is invoked from static data (.LC0). withStatic uses an array whose construction has been optimized as a constant (withStatic()::arr).

    – YSC
    5 hours ago














  • 3





    In the static case they may not be on the stack, but in a read-only section. Probably compiler dependent as well.

    – Matthieu Brucher
    5 hours ago






  • 3





    out of curiosity: do you have a real problem at hand, or is this just an academic exercise? (its a valid question in both cases)

    – user463035818
    5 hours ago






  • 1





    @user463035818 I am having discussion during code review ;)

    – bartop
    5 hours ago






  • 2





    depending on the reviewer that can be a real problem :P

    – user463035818
    5 hours ago






  • 4





    @Scheff withoutStatic builds the array each times it is invoked from static data (.LC0). withStatic uses an array whose construction has been optimized as a constant (withStatic()::arr).

    – YSC
    5 hours ago








3




3





In the static case they may not be on the stack, but in a read-only section. Probably compiler dependent as well.

– Matthieu Brucher
5 hours ago





In the static case they may not be on the stack, but in a read-only section. Probably compiler dependent as well.

– Matthieu Brucher
5 hours ago




3




3





out of curiosity: do you have a real problem at hand, or is this just an academic exercise? (its a valid question in both cases)

– user463035818
5 hours ago





out of curiosity: do you have a real problem at hand, or is this just an academic exercise? (its a valid question in both cases)

– user463035818
5 hours ago




1




1





@user463035818 I am having discussion during code review ;)

– bartop
5 hours ago





@user463035818 I am having discussion during code review ;)

– bartop
5 hours ago




2




2





depending on the reviewer that can be a real problem :P

– user463035818
5 hours ago





depending on the reviewer that can be a real problem :P

– user463035818
5 hours ago




4




4





@Scheff withoutStatic builds the array each times it is invoked from static data (.LC0). withStatic uses an array whose construction has been optimized as a constant (withStatic()::arr).

– YSC
5 hours ago





@Scheff withoutStatic builds the array each times it is invoked from static data (.LC0). withStatic uses an array whose construction has been optimized as a constant (withStatic()::arr).

– YSC
5 hours ago












4 Answers
4






active

oldest

votes


















7














Forget the array for a moment. That muddles two separate issues. You've got answers that address the lifetime and storage issue. I'll address the initialization issue.



void f() {
static const int x = get_x();
// do something with x
}

void g() {
const int x = get_x();
// do something with x
}


The difference between these two is that the first one will only call get_x() the first time that f() is called; x retains that value through the remainder of the program. The second one will call get_x() each time that g() is called.



That matters if get_x() returns different values on subsequent calls:



int current_x = 0;
int get_x() { return current_x++; }





share|improve this answer































    5















    And is there any danger associated with any of these solutions?




    Non-static is dangerous because the array is huge, and the memory reserved for automatic storage is limited. Depending on the system and configuration, that array could use about 30% of the space available for automatic storage. As such, it greatly increases the possibility of stack overflow.



    While an optimiser might certainly avoid allocating memory on the stack, there are good reasons why you would want your non-optimised debug build to also not crash.






    share|improve this answer

































      3















      What are the possible performance differences between these two if any?And is there any danger associated with any of these solutions?




      The difference depends exactly on how you use foo().



      1st case:(low probability): Your implementation is such that you will call foo() only once , maybe you have created separate function to divide code logic as practiced. Well in this case declaring as static is very bad, because a static variable or object remains in memory until programs ends . So just imagine that your variable occupying memory unnecessarily.



      2nd case:(high probability): Your implementation is such that you will call foo() again and again . Then non-static object will get allocated and de allocated again and again.This will take huge amount of cpu clock cycles which is not desired .Use static in this case.






      share|improve this answer































        1














        In this particular context, one point to consider regarding using static on a variable with initialization:



        From C++17 standard:




        6.7.1 Static storage duration [basic.stc.static]

        ...
        2 If a variable with static storage duration has initialization or a destructor with side effects, it shall not be eliminated even if it appears to be unused, except that a class object or its copy/move may be eliminated as specified in 15.8.







        share|improve this answer


























        • Actually, there are more differences: Its lifetime is different, for one....

          – CharonX
          2 hours ago











        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54942664%2fdoes-static-make-a-difference-for-a-const-local-variable%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        4 Answers
        4






        active

        oldest

        votes








        4 Answers
        4






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        7














        Forget the array for a moment. That muddles two separate issues. You've got answers that address the lifetime and storage issue. I'll address the initialization issue.



        void f() {
        static const int x = get_x();
        // do something with x
        }

        void g() {
        const int x = get_x();
        // do something with x
        }


        The difference between these two is that the first one will only call get_x() the first time that f() is called; x retains that value through the remainder of the program. The second one will call get_x() each time that g() is called.



        That matters if get_x() returns different values on subsequent calls:



        int current_x = 0;
        int get_x() { return current_x++; }





        share|improve this answer




























          7














          Forget the array for a moment. That muddles two separate issues. You've got answers that address the lifetime and storage issue. I'll address the initialization issue.



          void f() {
          static const int x = get_x();
          // do something with x
          }

          void g() {
          const int x = get_x();
          // do something with x
          }


          The difference between these two is that the first one will only call get_x() the first time that f() is called; x retains that value through the remainder of the program. The second one will call get_x() each time that g() is called.



          That matters if get_x() returns different values on subsequent calls:



          int current_x = 0;
          int get_x() { return current_x++; }





          share|improve this answer


























            7












            7








            7







            Forget the array for a moment. That muddles two separate issues. You've got answers that address the lifetime and storage issue. I'll address the initialization issue.



            void f() {
            static const int x = get_x();
            // do something with x
            }

            void g() {
            const int x = get_x();
            // do something with x
            }


            The difference between these two is that the first one will only call get_x() the first time that f() is called; x retains that value through the remainder of the program. The second one will call get_x() each time that g() is called.



            That matters if get_x() returns different values on subsequent calls:



            int current_x = 0;
            int get_x() { return current_x++; }





            share|improve this answer













            Forget the array for a moment. That muddles two separate issues. You've got answers that address the lifetime and storage issue. I'll address the initialization issue.



            void f() {
            static const int x = get_x();
            // do something with x
            }

            void g() {
            const int x = get_x();
            // do something with x
            }


            The difference between these two is that the first one will only call get_x() the first time that f() is called; x retains that value through the remainder of the program. The second one will call get_x() each time that g() is called.



            That matters if get_x() returns different values on subsequent calls:



            int current_x = 0;
            int get_x() { return current_x++; }






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered 3 hours ago









            Pete BeckerPete Becker

            58.2k442119




            58.2k442119

























                5















                And is there any danger associated with any of these solutions?




                Non-static is dangerous because the array is huge, and the memory reserved for automatic storage is limited. Depending on the system and configuration, that array could use about 30% of the space available for automatic storage. As such, it greatly increases the possibility of stack overflow.



                While an optimiser might certainly avoid allocating memory on the stack, there are good reasons why you would want your non-optimised debug build to also not crash.






                share|improve this answer






























                  5















                  And is there any danger associated with any of these solutions?




                  Non-static is dangerous because the array is huge, and the memory reserved for automatic storage is limited. Depending on the system and configuration, that array could use about 30% of the space available for automatic storage. As such, it greatly increases the possibility of stack overflow.



                  While an optimiser might certainly avoid allocating memory on the stack, there are good reasons why you would want your non-optimised debug build to also not crash.






                  share|improve this answer




























                    5












                    5








                    5








                    And is there any danger associated with any of these solutions?




                    Non-static is dangerous because the array is huge, and the memory reserved for automatic storage is limited. Depending on the system and configuration, that array could use about 30% of the space available for automatic storage. As such, it greatly increases the possibility of stack overflow.



                    While an optimiser might certainly avoid allocating memory on the stack, there are good reasons why you would want your non-optimised debug build to also not crash.






                    share|improve this answer
















                    And is there any danger associated with any of these solutions?




                    Non-static is dangerous because the array is huge, and the memory reserved for automatic storage is limited. Depending on the system and configuration, that array could use about 30% of the space available for automatic storage. As such, it greatly increases the possibility of stack overflow.



                    While an optimiser might certainly avoid allocating memory on the stack, there are good reasons why you would want your non-optimised debug build to also not crash.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited 5 hours ago

























                    answered 5 hours ago









                    eerorikaeerorika

                    83.8k662128




                    83.8k662128























                        3















                        What are the possible performance differences between these two if any?And is there any danger associated with any of these solutions?




                        The difference depends exactly on how you use foo().



                        1st case:(low probability): Your implementation is such that you will call foo() only once , maybe you have created separate function to divide code logic as practiced. Well in this case declaring as static is very bad, because a static variable or object remains in memory until programs ends . So just imagine that your variable occupying memory unnecessarily.



                        2nd case:(high probability): Your implementation is such that you will call foo() again and again . Then non-static object will get allocated and de allocated again and again.This will take huge amount of cpu clock cycles which is not desired .Use static in this case.






                        share|improve this answer




























                          3















                          What are the possible performance differences between these two if any?And is there any danger associated with any of these solutions?




                          The difference depends exactly on how you use foo().



                          1st case:(low probability): Your implementation is such that you will call foo() only once , maybe you have created separate function to divide code logic as practiced. Well in this case declaring as static is very bad, because a static variable or object remains in memory until programs ends . So just imagine that your variable occupying memory unnecessarily.



                          2nd case:(high probability): Your implementation is such that you will call foo() again and again . Then non-static object will get allocated and de allocated again and again.This will take huge amount of cpu clock cycles which is not desired .Use static in this case.






                          share|improve this answer


























                            3












                            3








                            3








                            What are the possible performance differences between these two if any?And is there any danger associated with any of these solutions?




                            The difference depends exactly on how you use foo().



                            1st case:(low probability): Your implementation is such that you will call foo() only once , maybe you have created separate function to divide code logic as practiced. Well in this case declaring as static is very bad, because a static variable or object remains in memory until programs ends . So just imagine that your variable occupying memory unnecessarily.



                            2nd case:(high probability): Your implementation is such that you will call foo() again and again . Then non-static object will get allocated and de allocated again and again.This will take huge amount of cpu clock cycles which is not desired .Use static in this case.






                            share|improve this answer














                            What are the possible performance differences between these two if any?And is there any danger associated with any of these solutions?




                            The difference depends exactly on how you use foo().



                            1st case:(low probability): Your implementation is such that you will call foo() only once , maybe you have created separate function to divide code logic as practiced. Well in this case declaring as static is very bad, because a static variable or object remains in memory until programs ends . So just imagine that your variable occupying memory unnecessarily.



                            2nd case:(high probability): Your implementation is such that you will call foo() again and again . Then non-static object will get allocated and de allocated again and again.This will take huge amount of cpu clock cycles which is not desired .Use static in this case.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered 5 hours ago









                            Abhishek GargAbhishek Garg

                            1268




                            1268























                                1














                                In this particular context, one point to consider regarding using static on a variable with initialization:



                                From C++17 standard:




                                6.7.1 Static storage duration [basic.stc.static]

                                ...
                                2 If a variable with static storage duration has initialization or a destructor with side effects, it shall not be eliminated even if it appears to be unused, except that a class object or its copy/move may be eliminated as specified in 15.8.







                                share|improve this answer


























                                • Actually, there are more differences: Its lifetime is different, for one....

                                  – CharonX
                                  2 hours ago
















                                1














                                In this particular context, one point to consider regarding using static on a variable with initialization:



                                From C++17 standard:




                                6.7.1 Static storage duration [basic.stc.static]

                                ...
                                2 If a variable with static storage duration has initialization or a destructor with side effects, it shall not be eliminated even if it appears to be unused, except that a class object or its copy/move may be eliminated as specified in 15.8.







                                share|improve this answer


























                                • Actually, there are more differences: Its lifetime is different, for one....

                                  – CharonX
                                  2 hours ago














                                1












                                1








                                1







                                In this particular context, one point to consider regarding using static on a variable with initialization:



                                From C++17 standard:




                                6.7.1 Static storage duration [basic.stc.static]

                                ...
                                2 If a variable with static storage duration has initialization or a destructor with side effects, it shall not be eliminated even if it appears to be unused, except that a class object or its copy/move may be eliminated as specified in 15.8.







                                share|improve this answer















                                In this particular context, one point to consider regarding using static on a variable with initialization:



                                From C++17 standard:




                                6.7.1 Static storage duration [basic.stc.static]

                                ...
                                2 If a variable with static storage duration has initialization or a destructor with side effects, it shall not be eliminated even if it appears to be unused, except that a class object or its copy/move may be eliminated as specified in 15.8.








                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited 2 hours ago

























                                answered 4 hours ago









                                P.WP.W

                                15.4k31453




                                15.4k31453













                                • Actually, there are more differences: Its lifetime is different, for one....

                                  – CharonX
                                  2 hours ago



















                                • Actually, there are more differences: Its lifetime is different, for one....

                                  – CharonX
                                  2 hours ago

















                                Actually, there are more differences: Its lifetime is different, for one....

                                – CharonX
                                2 hours ago





                                Actually, there are more differences: Its lifetime is different, for one....

                                – CharonX
                                2 hours ago


















                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54942664%2fdoes-static-make-a-difference-for-a-const-local-variable%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Benedict Cumberbatch Contingut Inicis Debut professional Premis Filmografia bàsica Premis i...

                                Monticle de plataforma Contingut Est de Nord Amèrica Interpretacions Altres cultures Vegeu...

                                Escacs Janus Enllaços externs Menú de navegacióEscacs JanusJanusschachBrainKing.comChessV