Search code examples
c#memory-managementstack-overflow

What is .net 8 x64 process default stack size (for stackalloc)


In my net 8 app I use Span/stackalloc to fast allocate some data structures. I use the following pattern

float[] myDataRent = null;
Span<float> myData = numberToAllocate <= maxStackAllocSize ? stackalloc float[numberToAllocate] : (myDataRentRent = ArrayPool<float>.Shared.Rent(numberToAllocate));
...
if( myDataRent != null )
    ArrayPool<float>.Shared.Return( myDataRent );

My performance measurements show a very high performance gain of stackalloc, so I would prefer to use stack allocation to as far as possible. Therefore I need to know the maximum safe value for maxStackAllocSize.

So what is the default stack size for 64 bit net core process? According to what I read it should be 4 mb (then I consider 2 mb safe to use for stackalloc), but GetCurrentThreadStackLimits check gives me something close to 1.5 mb and not a very round number. Don't know if I can trust it.


Solution

  • but GetCurrentThreadStackLimits check gives me something close to 1.5 mb and not a very round number

    The value is 0x180000, this number is configured in this file: Microsoft.NETCore.Native.Windows.targets. But this is not the maximum safe value, it is obvious that there are already many functions on the stack before entering the main method. This limitation can be increased by modifying the SizeOfStackReserve field in the PE header, but it is usually not recommended to allocate more space on the stack than one system page size (Environment.SystemPageSize)