Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How much space does string.Empty take in CLR

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

like image 670
Midhat Avatar asked Feb 26 '23 00:02

Midhat


2 Answers

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).

like image 64
Jon Skeet Avatar answered Feb 27 '23 16:02

Jon Skeet


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.

like image 23
Anders Zommarin Avatar answered Feb 27 '23 16:02

Anders Zommarin