简体   繁体   English

一个字符串在x64中占用多少字节?

[英]How many bytes does a string take up in x64?

For the purpose of learning, I'm trying to understand how C# strings are internally stored in memory. 为了学习,我试图了解C#字符串是如何内部存储在内存中的。

According to this blog post , C# string size is (x64 with .NET framework 4.0) : 根据此博客文章 ,C#字符串大小为(.NET Framework 4.0为x64):

26 + 2 * length

A string with a single character will take (26 + 2 * 1) / 8 * 8 = 32 bytes . 具有单个字符的字符串将占用(26 + 2 * 1) / 8 * 8 = 32 bytes This is indeed similar to what I measured. 这确实与我所测量的相似。

What puzzle me is what is in that 26 bytes overhead. 让我感到困惑的是这26个字节的开销是什么。

I have run the following code and inspected memory : 我已经运行了以下代码并检查了内存:

string abc = "abcdeg";
string aaa = "x";
string ccc = "zzzzz";

在此处输入图片说明

AFAIK those blocks are the following : AFAIK这些块如下:

  • Green : Sync block (8 bytes) 绿色:同步块(8字节)
  • Cyan : Type info (8 bytes) 青色:类型信息(8个字节)
  • Yellow : Length (4 bytes) 黄色:长度(4个字节)
  • Pink : The actual characters : 2 bytes per char + 2 bytes for NULL terminator. 粉色:实际字符:每个字符2个字节+ NULL终止符2个字节。

Look at the "x" string. 查看“ x”字符串。 It is indeed 32 bytes (as calculated). 实际上是32个字节(计算得出)。

Anyway it looks like the end of the string if padded with zeroes. 无论如何,如果用零填充,它看起来像字符串的结尾。 The "x" string could end up after the two bytes for NULL terminator and still be memory aligned (thus being 24 bytes). “ x”字符串可能会在NULL终止符的两个字节之后结束,并且仍然是内存对齐的(因此是24个字节)。 Why do we need an extra 8 bytes ? 为什么我们需要额外的8个字节?

I have experimented similar results with other (bigger) string sizes. 我已经对其他(更大)的字符串大小进行了类似的实验。 It looks like there is always an extra 8 bytes. 看起来总会有8个字节。

As Hans Passant suggested, there is an extra field added at the end of string object which is 4 bytes (in x64, it might require another 4 bytes extra, for padding). 正如Hans Passant所建议的,在字符串对象的末尾添加了一个额外的字段,该字段为4个字节(在x64中,可能需要另外4个字节来填充)。

So in the end we have : 所以最后我们有了:

= 8 (sync) + 8 (type) + 4 (length) + 4(extra field) + 2 (null terminator) + 2 * length 
= 26 + 2 * length

So Jon Skeet's blog post was right (how could it be wrong ?) 因此,乔恩·斯基特(Jon Skeet)的博客文章是对的(怎么可能错了?)

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

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