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.
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.
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.)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With