问题描述
我读了一篇让我对内存分配感到困惑的文章,其中指出:
单个对象存储在堆上,而静态类存储在存储在堆栈中.
链接是:
I read an article which confused me about memory allocation, which stated:
But in some Stackoverflow questions, such as
How is memory allocated for a static variable?
It was described like
So I am confused with stack or heap storage for static classes. How is memory allocated for a static class and why? How is memory allocated for singleton class?
There are four possible root types in .NET Framework:
- Stack references: references to local objects. Such roots live during a method execution.
- Static references: references to static objects. These roots live the entire app domain life time.
- Handles: typically, these are references used for communication between managed and unmanaged code. Such roots must live at least until the unmanaged code needs "managed" objects.
- Finalizer references: references to objects waiting to be finalized. These roots live until the finalizer is run.
https://www.jetbrains.com/help/dotmemory/Analyzing_GC_Roots.html
High Frequency Heap
Static data and constants defined in a C# program are stored on the heap. Since they exist for the lifetime of the application, they do not need to be garbage collected and are therefore stored in a loader heap, rather than the normal Garbage Collected heap. Specifically, static data is stored on the high-frequency heap–one of the loader heaps that exists for each AppDomain.
Static Data and Constants Are Stored on the Heap
这篇关于静态类内存分配 C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!