Find Size of Object Instance in Bytes in C#

how to find size of object in memory?

The BinaryFormatter tells you how many bytes it needs to serialize the class to binary. This is very different from the size a class takes in memory. For instance, the BinaryFormatter writes information about the type into the stream.

The size that an object uses in memory is not defined at compile time but at runtime, since the JIT compiler decides on the final layout. Now comes the question how to find out the size. While I have a solution for structs (create an array, do pointer arithmetic), I am not sure how to find that out for classes. One solution would be to define your class MemberStateModel as a struct, measure it, then turn back to a class, assuming it will have the same size.

You can also estimate the size, by counting the size of the fields as a lower bound (since padding occurs). If your class has references to other class instances, then it gets nearly impossible to estimate.

Get the size, in bytes, of how much a string will occupy when written to a file?

A file may begin with a byte order mark (called BOM) that helps the reader to detect what encoding was used.

The BOM for UTF8 is 3 bytes EF,BB,BF

For UTF16 (Encoding.Unicode) 2 bytes FEFF (encoded as either big endian or little endian depending on the encoding)

For UTF32 4 bytes 0000FEFF

C# Object Size Overhead

Typically, there is an 8 or 12 byte overhead per object allocated by the GC. There are 4 bytes for the syncblk and 4 bytes for the type handle on 32bit runtimes, 8 bytes on 64bit runtimes. For details, see the "ObjectInstance" section of Drill Into .NET Framework Internals to See How the CLR Creates Runtime Objects on MSDN Magazine.

Note that the actual reference does change on 32bit or 64bit .NET runtimes as well.

Also, there may be padding for types to fit on address boundaries, though this depends a lot on the type in question. This can cause "empty space" between objects as well, but is up to the runtime (mostly, though you can affect it with StructLayoutAttribute) to determine when and how data is aligned.

How to know the size of the string in bytes?

You can use encoding like ASCII to get a character per byte by using the System.Text.Encoding class.

or try this

  System.Text.ASCIIEncoding.Unicode.GetByteCount(string);
System.Text.ASCIIEncoding.ASCII.GetByteCount(string);


Related Topics



Leave a reply



Submit