Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disadvantages of using large variables/arrays on the stack?

What are the disadvantages, if any, of defining large arrays or objects on the stack? Take the following example:

int doStuff() {
   int poolOfObjects[1500];
   // do stuff with the pool
   return 0;
}

Are there any performance issues with this? I've heard of stack overflow issues, but I'm assuming that this array isn't big enough for that.

like image 446
void.pointer Avatar asked Jan 30 '12 23:01

void.pointer


3 Answers

Stack overflow is a problem, if

  • the array is larger than the thread stack

  • the call tree is very deep, or

  • the function uses recursion

In all other cases, stack allocation is a very fast and efficient way to get memory. Calling a large number of constructors and destructors can be slow, however, so if your constructor/destructor are non-trivial, you might want to look at a longer-lived pool.

like image 52
Ben Voigt Avatar answered Nov 09 '22 16:11

Ben Voigt


As you have mentioned, overrunning the stack is the primary issue. Even if your particular case isn't very large, consider what will happen if the function is recursive.

Even worse, if the function is called from a recursive function, it may be inlined - thus leading to "surprise" stackoverflow problems. (I've run into this issue multiple times with the Intel Compiler.)


As far as performance issues go, these are better measured than guessed. But having a very large array on the stack could potentially hurt data-locality if it separates other variables.

Other than that, stack allocation is dirt-cheap and faster than heap allocation. On some compilers (like MSVC), using more than 4k stack will make the compiler generate a buffer security check. (But it can be disabled though.)

like image 22
Mysticial Avatar answered Nov 09 '22 15:11

Mysticial


https://github.com/kennethlaskoski/SubtleBug

This code contains a bug that I call subtle because the binary runs flawlessly on iOS Simulator and crashes shamefully on a real device. Spoiler ahead: what happens on a real device is a classic stack overflow due to allocation of a very large variable. The simulator uses the much larger x86 stack, so all goes well. http://en.wikipedia.org/wiki/Stack_overflow#Very_large_stack_variables

like image 1
Kenneth Laskoski Avatar answered Nov 09 '22 16:11

Kenneth Laskoski