3 ms·
That looks more like the effect of a bad compiler. On most modern CPUs, including Intel/AMD & ARM-based, memory accesses with relative-addressing to the stack
by adrian_b 1y ago
That looks more like the effect of a bad compiler.
On most modern CPUs, including Intel/AMD & ARM-based, memory accesses with relative-addressing to the stack have at least the same performance if not much better performance than memory accesses through pointers to the heap. The stack is also normally cached automatically by the memory prefetcher.
So whichever was the cause of your performance increase was not an inefficiency of the stack accesses, but some other difference in the code generated by the compiler. Such an unexpected and big performance difference could normally be caused only by a compiler bug.
A special case when variables allocated in the stack can lead to low performance is when a huge amount of variables are allocated or many arrays are allocated, and then they are only sparsely used and the initial stack is much smaller. Then any new allocation of an array or big bunch of variables may exceed the stack size, which will cause a page fault, so that the operating system will grow the stack by one memory page.
This kind of transparent memory allocation by page faults can be much slower than the explicit memory allocation done by malloc or new. This is why big arrays should normally be allocated either statically or in the heap.
- osigurdson 1y agoWhat they are saying is the stackalloc approach causes no GC pressure. You can run that in a tight / infinite loop with essentially no downside. Using a regular heap allocated array in the same situation will hammer the GC. C# doesn't do escape analysis and automatically put things on the stack like (for example) Go does. However the stack size is limited in C# so I wouldn't suggest going too crazy with stackalloc and deep stacks / recursion. You don't want a stack overflow!
- ygra 1y ago> C# doesn't do escape analysis and automatically put things on the stack There has been work ongoing in this direction since .NET 9 at least, but the effect is very limited currently. The following code however, has no allocations at runtime, despite having an object creation in the code: https://sharplab.io/#v2:C4LghgzgtgPgAgJgIwFgBQcDMACR2DC2A3utmbjgJYB2w2AYgPaMAUAlMaedwG5gBO2MNgC82agFMA7thrAA2gHYAugG4u3MnEVCAdABkJ1AObAAFurTcAvumtA= https://sharplab.io/#v2:C4LghgzgtgPgAgJgIwFgBQcDMACR2DC2A3ut...
- Izikiel43 1y ago> C# doesn't do escape analysis In net9 they started on that, and on net10 they have improved it, you can check the performance blogpost by Stephen toub for net10 for more info