Disadvantages of using large variables/arrays on the stack?

百般思念 提交于 2019-12-01 18:20:00

问题


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.


回答1:


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.




回答2:


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.)




回答3:


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




回答4:


The stack overflow issues should be your main technical concern, but if this code is going to be used by others its careful to consider if the magic size of 1500 might disrupt someone's usage of this function.



来源:https://stackoverflow.com/questions/9072415/disadvantages-of-using-large-variables-arrays-on-the-stack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!