Reputation: 629
This is a very general question abut C# .NET. Some techniques about performance optimization are always trying to allocate objects on stack instead of heap if possible; using stackalloc
instead of normal Array
, or using struct type as a local variable instead of class. My question is why allocating objects on stack improves the performance? In my view, memory is memory, so the mean time to allocate object would be the same. Is is just because of avoiding garbage collection?
Upvotes: 1
Views: 598
Reputation: 1627
Garbage Collector is indeed an important factor when the discussion involves unmanaged code, since stack allocation (with stackalloc) would demand less from it. Note that, in heap's case, an array deallocation would be required from garbage collector. On the other hand, for managed code, the allocation is made by default (you can't choose how) - reference types are allocated in the heap, while value types in stack.
Upvotes: 1