Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is variable allocated on stack if i return before its declaration?

Tags:

c++

Assume i have a function whose rough structure looks like this:

int aRecursiveFunction(const SomeLargeStructure *a, int x) {
    if (end recursion)
        return 0;
    // ...
    if (something that is mostly true)
        return aRecursiveFunction(a, x+1)+1;
    // ...
    SomeLargeStructure copy = *a;
    alter(&copy);
    return aRecursiveFunction(&copy, x);
}

What i need to know is, for performance reasons, whether the space for copy (which is a large structure) will be created on the stack in the 90 % of cases where the function ends before this point. Or does it actually not even matter? Does it depend on the compiler? Is it better to separate this part as another function?

Thanks.

EDIT: To clarify, sizeof(SomeLargeStructure) is around 500, it only has basic types and arrays (no special constructors or assignment operators etc.).

EDIT 2: Alright, the conclusion seems to be that the stack space probably will be allocated every time but it doesn't impact performance. Stack overflow is not an issue here, so case closed.

like image 231
Detheroc Avatar asked Oct 20 '14 09:10

Detheroc


1 Answers

On most platforms, the maximum stack space that might be needed is allocated on function entry. But usually allocating stack space is just addition, so the amount of space allocated has no effect on performance.

Your question reads like premature optimization to me though. This isn't an algorithmic issue and you don't have a measured performance issue. So why are you even thinking about micro-optimizations?

like image 143
David Schwartz Avatar answered Oct 04 '22 17:10

David Schwartz