Allocator.Temp vs stackalloc

Is stackalloc faster than allocator.temp native array?

apparently allocator.temp memory is not stack but actually preallocated heap that is disposed every frame.

so would it be a good idea to replace all my allocator.temp allocations with stackalloc?

1 Like

Stack alloc gets deallocated at the end of your method. If it makes sense for you, sure! Just be aware of the pros and cons: Dos and Don'ts of stackalloc
TDLR: Be careful with the size of your stack allocs

3 Likes

Side note, burst 1.6.1 now supports Span so you can use stackalloc with that!

2 Likes

I guess allocator.temp is using a preallocated linear allocator, and never releases it even if you call dispose and set the pointer back every frame. Since the stack and heap physically run on the same hardware, the only difference is in the overhead of the allocator, which should be minimal, especially in the production build.

With stackalloc you have to be careful, because the stack size is relatively small and therefore not suitable for larger amounts of data or in loops and recursions, this can quickly lead to a stack overflow. Visual studio warns you if you use a stackalloc in a loop.

2 Likes