静态类内存分配 C# [英] Static class memory allocation where it is stored C#

查看:74
本文介绍了静态类内存分配 C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读了一篇让我对内存分配感到困惑的文章,其中指出:

<块引用>

单个对象存储在堆上,而静态类存储在存储在堆栈中.

链接是:

I read an article which confused me about memory allocation, which stated:

Singleton objects are stored on the heap while static classes are stored on the stack.

link is : http://www.dotnetjalps.com/2013/06/Static-vs-Singleton-in-Csharp-Difference-between-Singleton-and-Static.html

But in some Stackoverflow questions, such as

How is memory allocated for a static variable?

It was described like

Static variables are stored on the heap, regardless of whether they are declared as a reference type or a value type. There is only one slot in total no matter how many instances are created.

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#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆