Marshal.AllocHGlobal vs stackalloc

Arsium ***** 331 Reputation points
2021-02-07T13:00:46.907+00:00

What is the difference(s) between Marshal.AllocHGlobal and stackalloc ?

Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Timon Yang-MSFT 9,606 Reputation points
    2021-02-08T03:15:36.663+00:00

    stackalloc uses stack memory, while Marshal.AllocHGlobal uses unmanaged memory.

    An engineer from the .Net team wrote a blog about different forms of memory, please check.

    Span – Adam Sitnik – .NET Performance and Reliability

    In order to avoid that this blog is no longer available one day in the future, I extract a part of the content related to the current issue.

    Stack memory - allocated on the Stack with the stackalloc keyword. Very fast allocation and deallocation. The size of the Stack is very small (usually < 1 MB) and fits well into CPU cache. But when you try to allocate more, you get StackOverflowException which can not be handled and immediately kills the entire process. Usage is also limited by the very short lifetime of the stack - when the method ends, the stack gets unwinded together with its memory. Stackalloc is commonly used for short operations that must not allocate any managed memory.

    Unmanaged memory - allocated on the unmanaged heap (invisible to GC) by calling Marshal.AllocHGlobal or Marshal.AllocCoTaskMem methods. This memory must be released by the developer with an explicit call to Marshal.FreeHGlobal or Marshal.FreeCoTaskMem. By using it we don’t add any extra pressure for the GC. It’s most commonly used to avoid GC in scenarios where you would normally allocate huge arrays of value types without pointers.


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.