Reputation: 4929
First part:
I have a string...
string sTest = "This is my test string";
How can I (manually, without code) determine the SizeOf the string? What should it end up being? How do you get that size?
Second Part:
I have a class...
[StructLayout(LayoutKind.Sequential)]
public class TestStruct
{
public string Test;
}
I use it...
TestStruct oTest = new TestStruct();
oTest.Test = "This is my test string";
Are there any differences in size from the first part to the second part?
Update:
The point of this is to use the size as a way to create a memory map file.
long lMapSize = System.Runtime.InteropServices.Marshal.SizeOf(oTest);
mmf = MemoryMappedFile.CreateOrOpen("testmap", lMapSize);
Just thought it was worth noting. Currently lMapSize = 4. Which confuses the ... out of me! Thanks everyone!
Upvotes: 3
Views: 400
Reputation: 2017
string
is a reference type, so field inside other class or struct or local method variable will be a pointer - IntPtr
. Size of pointer is 32 bit on 32 bit pc and 64 for 64.
If you want to know size of string itself, you need to know which encoding you are going to use. Encoding.UTF8.GetByteCount("aaa")
will return size of "aaa"
in UTF8 encoding. But this will return only size of string, not .net object size.
Looks like there is no accurate way to calculate size of object from code. If you want to know what's going on in your application there is some memory profilers for it, just search 'C# memory profiler'. I've used only mono profiler with heap-shot, so I can't recomend you which of profilers is good.
Another way is to use WinDBG with sos.dll and sosex.dll. Here you can find example of using sos.dll.
byte[] bytes;
using (MemoryStream stream = new MemoryStream())
{
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, myObject);
bytes = stream.ToArray();
}
using (MemoryStream stream = new MemoryStream(bytes))
{
IFormatter formatter = new BinaryFormatter();
myObject = formatter.Deserialize(stream);
}
Upvotes: 2