c++optimizationstack-memorystatic-memory-allocation

Optimizing frequently called function with large local variables (C++)


Let's say there is a function that I need to call millions of times. Arithmetic operations performed by this function are not so heavy, so the only thing that matters is how fast all variables are allocated. Also we assume that the variable is always allocated on stack. The simplest case example:

void doSomething(){
    int aReallyLargeVariable[10000];
    ...performing a few light operations on that variable and returning nothing...
}

I know that when function returns all it's variables are destroyed,so
wouldn't it be better to cache this variable by making it static or global? What would be the best way to optimize it?


Solution

  • It is not the allocation that will cause performance problem. The problem is to initialize it so when

        int aReallyLargeVariable[10000];
    

    won't take many time the

        int aReallyLargeVariable[10000] = {0};
    

    will do. Also creating huge objects dynamically can cause a problem.

    If you have a function that has not very heavy logic and is using only primitive types just define it as inline and do not worry about performance.

    If you need to define big amount of object think about another data structure like stack or vector that won't need to have 1000 or more elements