Why stack is faster than heap and what exactly is stack?

You’re right, I did blindly make some claims about automatic arrays, so I’ve put together some simple investigations on godbolt. I made a subroutine that takes in a length parameter, creates an automatic array, and then passes that to an external subroutine.

gfortran’s default seems to be to call malloc() for the automatic array: Compiler Explorer
If I add -fstack-arrays, it doesn’t, and just adjusts the stack pointer: Compiler Explorer
Intel’s default is to put it on the stack: Compiler Explorer
Adding the -heap-arrays flag shows that now it calls for_allocate(), (whatever that is): Compiler Explorer. Changing the size parameter of -heap-arrays has no effect on the assembly.

So it seems that I was wrong. The two compilers that I have access to do NOT make a runtime-decision about where to put the arrays. That doesn’t preclude a compiler from doing that (it could very well be done). The decision is currently made at compile-time through the use of compiler flags.

However, I still stand by my conclusion that automatic arrays should be avoided, precisely because of this ambiguity. Different compilers do different things, and I don’t really like that.

1 Like