创建新类或结构时.NET中的内存使用情况 [英] Memory usage in .NET when creating a new class or struct

查看:85
本文介绍了创建新类或结构时.NET中的内存使用情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Int的大小为4个字节,如果我在程序中创建一个新的Int,则其内存消耗将增加4个字节.对吧?

Int has a size of 4 bytes, if I create a new Int in my program will incresse its memory consumption by 4 bytes. Right?

但是如果我有这堂课

public class Dummy{
    private int;
}

我的新班级将使用多少内存?如果是结构,内存消耗会更低吗?我认为 reference 本身也会消耗一些内存.

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.

推荐答案

一个单个引用在32位进程中占4个字节,在64位进程中占8个字节.引用是类的标准开销(因为它们是引用类型).结构不会产生引用(很好,忽略任何可能的装箱),并且通常是其内容的大小.我不记得类是否还有更多开销,不要这样认为.

A single reference either takes 4 bytes on 32-bit processes or 8 bytes on 64-bit processes. 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):

使用新建"在结构上分配它在堆或堆栈上?

如评论中所述,只有类的实例才会消耗此引用开销,并且仅当某个地方有引用时才消耗.如果没有引用,则该项目可用于GC-我不确定在没有任何引用的情况下堆上的类的大小是多少,我认为这是其内容的大小.

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.

确实,类没有可依赖的真实大小".而且 最重要 ,这实际上不是使用类或结构的决定因素(但是您倾向于找到一些准则,指出大约16个字节或以下的类型是合适的)结构,以及以上的趋向于类).对我来说,决定因素是预期的用途.

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). For me the deciding factor is intended usage.

在谈论结构时,我不得不提供以下链接:为什么可变结构邪恶"?

这篇关于创建新类或结构时.NET中的内存使用情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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