开发者

Why is a 1 character .NET string 32 bytes in x64?

I've been trying to figure out the overhead of a string in .NET 4 x64. This is what I've got so far.

  • 16 byte object header for x64
  • 4 bytes for the stringLength field (arrayLength is gone in .NET 4)
  • (length + 1) * 2 bytes for the string content (UTF-16, null terminated)

So you'd expect a 1 character string to be 16 + 4 + 4 = 24 bytes. It's divisible by 8 so it shouldn't need any padding.

But when I look at the sizes in WinDbg I see them taking 32 bytes. When I !dumpobject them they say their size is 28 bytes, which is what I 开发者_开发技巧assume is getting rounded up to 32. What's going on? Is there another round of memory alignment happening?


I suspect that the first character is aligned on an 8-byte boundary on x64, so that when passed as a pointer to unmanaged code, it's a properly-aligned pointer. Your figures certainly fit in with the ones I got measuring string size recently, leading to formulae of:

32 bit: 14 + length * 2 (rounded up to 4 bytes) 
64 bit: 26 + length * 2 (rounded up to 8 bytes)

So in a 64 bit CLR, even a 0-length string takes 32 bytes by my reckoning.


Rounding up to paragraph (16-byte) boundaries to optimize cache line fills on Intel processors?


From what I understand you can't rely on anything on the implementation side with .NET - just because it is x bytes on your machine, doesn't mean it is x bytes on some other machine/.NET version. i.e. it is dangerous to do anything in code with knowledge of the internal struct layout of .NET classes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜