How much space does string.Empty take in CLR

泪湿孤枕 提交于 2019-12-21 19:44:16

问题


How much space does string.Empty take in CLR?
I'm guessing it's just one byte for the NULL character.


回答1:


No, the string is a complete object, with an object header (containing a type reference, sync block etc), length, and whatever characters are required... which will be a single null character (two bytes) and appropriate padding to round up to 4 or 8 bytes overall.

Note that although strings in .NET have a length field, they're still null-terminated for the sake of interop. The null character is not included in the length.

Of course, string.Empty will only refer to a single object no matter how many times you use it... but the reference will be 4 or 8 bytes, so if you have:

string a = string.Empty;
string b = string.Empty;
string c = string.Empty;

that will be three references (12 or 24 bytes) all referring to the same object (which is probably around 20 or 24 bytes in size).




回答2:


I think that each .NET object need an 8 byte header on 32-bit systems and 16-byte header on 64-bit systems. But as string.Empty is shared (if used as the given constant) then only one instance is needed (as it is immutable and thus shared - any usage of it in an application will not matter as my guess is that the .NET framework already uses it internally) and therefore only the pointer is needed (4 or 8 bytes depending on 32- or 64-bit host).

But the size of the string.Empty itself should be 12-bytes or 20-bytes on 32-bit and 64-bit hosts.




回答3:


a byte per character...Null takes i character ...



来源:https://stackoverflow.com/questions/5079753/how-much-space-does-string-empty-take-in-clr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!