gpt4 book ai didi

c# - 如何检查引用需要多少字节?

转载 作者:太空宇宙 更新时间:2023-11-03 17:53:41 25 4
gpt4 key购买 nike

来自 C# 5.0 in a Nutshell: The Definitive Reference在第 22 页;

Reference types require separate allocations of memory for the reference and object. The object consumes as many bytes as its fields, plus additional administrative overhead. The precise overhead is intrinsically private to the implementation of the .NET runtime, but at minimum the overhead is eight bytes, used to store a key to the object’s type, as well as temporary information such as its lock state for multithreading and a flag to indicate whether it has been fixed from movement by the garbage collector. Each reference to an object requires an extra four or eight bytes, depending on whether the .NET runtime is running on a 32- or 64-bit platform.



我不太确定我是否完全理解这个大胆的部分。它说在 32 位平台上一个引用需要四个字节,在 64 位平台上它需要八个字节。

所以,假设我们有
string s = "Soner";

我怎样才能检查这个 s 有多少字节?引用要求?

最佳答案

您可以使用 Environment.Is64BitProcess .如果是,则每个引用将是 8 个字节。如果不是,每个引用将是 4 个字节。引用的类型和它所引用的对象的内容是无关紧要的。

编辑:正如现在已删除的答案中所述, IntPtr.Size 甚至更简单。

编辑:正如评论中所指出的,虽然目前 CLR 中的所有引用都是相同的大小,但它有可能在某些时候会走上与 Hotspot 类似的路径,它在许多情况下使用“压缩 oops”将引用存储为 32 -bit 值,即使在 64 位进程中(不限制可用内存)。

关于c# - 如何检查引用需要多少字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17477397/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com