1

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?

shumach5
  • 551
  • 5
  • 19
  • 1
    take look at this answer https://stackoverflow.com/questions/785226/practical-use-of-stackalloc-keyword][1] – Mohammad May 09 '20 at 03:48
  • Thanks, I saw the article, which says allocating an object on stack is faster than on heap, but why allocation on stack is faster than heap? – shumach5 May 09 '20 at 04:57
  • 1
    I think it is only because of garbage collector. It would demand less from it, as with heap you also need to deallocate arrays – Pedro Coelho May 09 '20 at 05:04
  • Stack allocation just involves incrementing a stack pointer, heap allocation needs to find free space, their names actually mean something, is it easier to allocate to a stack, then find a free spot in a heap... There is also GC considerations, the GC considers everything on the stack as in play (until its not), its management is trivial and has a lot less overhead.. all in all, unless you have a specific design goal or problem I would focus your programming efforts on other things – TheGeneral May 09 '20 at 06:35
  • "memory is just memory" is a broken mental model. CPU register, L1, L2, L3 cache and main store (RAM) have drastically different access times. Stack space is very cheap to allocate since no locks are necessary (always thread-safe) and usually readily available in the L1 cache. You can't allocate objects in the stack, it can only store values. Value types exist in C# to increase the odds for getting the fastest available memory, CPU registers. – Hans Passant May 09 '20 at 09:59
  • @HansPassant, So you mean value types could populate L1 cache of CPU, and even if the value types are allocated on stack area of RAM, it is populated with no locks. Those factors increase the performance, correct? – shumach5 May 10 '20 at 06:58

1 Answers1

1

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.

Pedro Coelho
  • 1,411
  • 3
  • 18
  • 31