简体   繁体   English

创建新类或结构时.NET中的内存使用情况

[英]Memory usage in .NET when creating a new class or struct

Int has a size of 4 bytes, if I create a new Int in my program will incresse its memory consumption by 4 bytes. Int的大小为4个字节,如果我在程序中创建一个新的Int将使其内存消耗增加4个字节。 Right? 对?

But if I have this class 但如果我有这门课

public class Dummy{
    private int;
}

How much memory will my new class use? 我的新课程将使用多少内存? Will be memory consumption be lower if it was a struct? 如果它是一个结构,内存消耗会更低吗? I think that the reference itself will also consume some memory. 我认为引用本身也会消耗一些内存。

A single reference either takes 4 bytes on 32-bit processes or 8 bytes on 64-bit processes. 单个引用要么在32位进程上占用4个字节,要么在64位进程上占用8个字节。 A reference is a standard overhead on classes (as they are reference types). 引用是类的标准开销(因为它们是引用类型)。 Structs do not incur references (well, ignoring any potential boxing) and are the size of their content usually. 结构不会引起参考(好吧,忽略任何潜在的拳击)并且通常是其内容的大小。 I cannot remember if classes have any more overhead, don't think so. 我不记得班级是否有更多的开销,不这么认为。

This question delves into class vs struct (also provided in the question comments): 这个问题深入研究了类与结构(也在问题评论中提供):

Does using "new" on a struct allocate it on the heap or stack? 在结构上使用“new”在堆或堆栈上分配它吗?

As stated in the comments, only instances of a class will consume this reference overhead and only when there is a reference somewhere. 如注释中所述,只有类的实例才会消耗此引用开销,并且只有在某处有引用时才会消耗此引用开销。 When there are no references, the item becomes eligible for GC - I'm not sure what the size of a class is on the heap without any references, I would presume it is the size of its content. 当没有引用时,该项目符合GC的条件 - 我不确定在没有任何引用的情况下类的大小是什么,我认为它是其内容的大小。

Really, classes don't have a true "size" that you can rely on. 实际上,课程没有你可以依赖的真正“大小”。 And most importantly this shouldn't really be the deciding factor on using classes or structs (but you tend to find guidelines stating that types at or below roughly 16 bytes can be suitable structs, and above tends towards classes). 最重要的是,这不应该是使用类或结构的决定因素(但是你倾向于找到指导说明大约16字节或以下的类型可以是合适的结构,并且上面倾向于类)。 For me the deciding factor is intended usage. 对我来说,决定因素是预期用途。

When talking about structs, I feel obliged to provide the following link: Why are mutable structs “evil”? 在谈论结构时,我觉得有必要提供以下链接: 为什么可变结构“邪恶”?

A class is a reference type and is located a the heap ( and will be remove there from the garbabe collector). 类是引用类型,位于堆(并将从garbabe收集器中删除)。 A struct ist value type and is stored on the stack. struct ist值类型并存储在堆栈中。
In case of your example Microsoft recommends a value type (struct), because a reference type causes too much overhead. 在您的示例的情况下,Microsoft建议使用值类型(struct),因为引用类型会导致过多的开销。

If you're interested in this topic then take a look into the book "CLR via C#" from Jeffrey Richter. 如果您对此主题感兴趣,请查看Jeffrey Richter的书“CLR via C#”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM