I need to know how much bytes my object consumes in memory (in C#). for example how much my Hashtable
, or SortedList
, or List<String>
.

- 153,850
- 22
- 249
- 325

- 14,191
- 20
- 61
- 77
-
3And http://stackoverflow.com/questions/207592/getting-the-size-of-a-field-in-bytes-with-c – Jon Skeet Mar 03 '09 at 09:14
-
and http://stackoverflow.com/questions/555929/c-memory-usage-of-an-object/556061#556061 – Pete Kirkham Mar 03 '09 at 10:09
-
1Any container is a relatively small object that holds a reference to some data storage (usually an array) outside the actual container object - and that in turn holds references to the actual objects you added to the container. So the question how much memory a List takes is not even well defined - the size of the list object itself, memory allocated by the list object, total size for everything in the list and the amount of memory that will be freed when the list is collected are all different values. – Nir Mar 03 '09 at 09:17
-
See the benchmarks in the test app I have created: https://github.com/scholtz/TestDotNetCollectionsMemoryAllocation – Scholtz Apr 16 '19 at 09:39
-
If you are using Visual Studio, you can use the new .NET Object Allocation Tool: https://devblogs.microsoft.com/visualstudio/net-object-allocation-tool-performance/ – Ricky Han Jun 21 '22 at 00:54
6 Answers
this may not be accurate but its close enough for me
long size = 0;
object o = new object();
using (Stream s = new MemoryStream()) {
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(s, o);
size = s.Length;
}

- 7,300
- 10
- 40
- 88

- 11,388
- 19
- 63
- 83
-
160This will put so much more. It adds the DLL name and version, ... **this is not a way to calculate object size.** – Aliostad Nov 01 '11 at 14:36
-
9I agree that this is _NOT_ a good way to calculate object size. Serialization may be a rough estimate of entropy, but provides no useful information about memory consumption. This is a complex question without an easy solution. – Henry Merriam Jan 13 '12 at 18:55
-
2I tried your method with List
before and after populating with items and it didn't seem to work returning same value - 41. Would you know the reson for it? – Jan 19 '12 at 15:45 -
Well I can't see your code but it works fine with List
... static void Main(string[] args) { var a = new List – Rush Frisby Jan 19 '12 at 22:26(); var b = new List (); var c = new List (); for (int i=0; i<100; i++) b.Add(i); for (int i=0; i<200; i++) c.Add(i); Console.WriteLine(GetSize(a)); // 205 Console.WriteLine(GetSize(b)); // 717 Console.WriteLine(GetSize(c)); // 1229 Console.ReadKey(); } static long GetSize(object o) { long size = 0; using (Stream s = new MemoryStream()) { var formatter = new BinaryFormatter(); formatter.Serialize(s, o); size = s.Length; } return size; } -
2I have the same problem: the length of a list is 41. The entire content of the stream is "\0\0\0\0����\0\0\0\0\0\0\0\0\0\0\rSystem.Object\0\0\0\0\v", retrieved with `s.Position=0; var sr = new System.IO.StreamReader(s); string str = sr.ReadToEnd();` – HugoRune Jun 06 '12 at 12:52
-
5Lists in C# are preallocated to whatever sizes the framework designers decided to go with, and then increased when needed. By default it's probably something like 10 elements. So you won't notice any size difference until you add enough elements to require more memory to be allocated. – Michael Yoon Oct 24 '12 at 22:59
-
1Yeah.. Not so accurate... I also got a 41 when I tried it on a list of objects – dreamerkumar Nov 29 '12 at 20:26
-
2if you get 41, you need to replace the object (object o = new object()) with the actual object you want to meassure ;). this is just a dummy – DanielG Nov 05 '14 at 13:20
-
A Bitmap 8bpp (1 byte per pixel) with size 1000x1000 should have 1 MB. Using this method, I get 2.094 KB. Why?? – Pedro77 Jan 20 '15 at 23:32
-
It will probably vary depending the state of your object. I don't use Bitmap much so I don't know what kinds of things you would typical do with it but with a blank 1000x1000 Bitmap in .NET fiddle I get 4169. https://dotnetfiddle.net/9Du1W0 – Rush Frisby Feb 19 '15 at 01:22
-
if you want to know "well arranged" how much objects allocate memory, why don't try Performance Profiler in VS? in settings -> General set .NET object allocation information to true and that is it. This is very simple and fastest way in my opinion. – st35ly Mar 19 '15 at 21:38
-
Can anyone comment if it is safe to assume this will only report **larger** than real memory consumption? I'm thinking in debug this could be used for a conservative estimate... for guestimating cache sizes for example – KCD Aug 25 '15 at 04:44
-
-
2@MatthieuCharbonnier Are you working in Notepad? LOL. http://stackoverflow.com/questions/28193622/how-do-i-quickly-resolve-namespaces-in-visual-studio-2015 – Rush Frisby Jul 19 '16 at 18:43
-
In order for this operation to not take up any additional memory, you can use a null stream. In other words, if you are checking the memory size of a big object, you don't have to waste that much memory again just to figure out it's size. Just serialize it to a null stream (the bytes don't get saved, but the bytes get counted) and get the byte count at the end. – N73k Sep 17 '16 at 22:31
-
@KCD What you say makes sense. I'll try to build up some proof on that. Thanks for pointing me in a general direction. – tfrascaroli Oct 03 '16 at 21:36
-
29
-
I tried this method to determine the difference in size of an array of ints and an array of longs. It gave me the same answer as using GC.GetTotalMemory before and after each allocation. So I think it's pretty accurate. – carlin.scott May 21 '19 at 23:54
-
What if the object creates a memory leak? Serialisation won't show you that. What if the object does a huge amount of string manipulation and saves the results into a static class? Once again this won't be shown up. What if the object has a parallel foreach loop that does some huge process that takes up 3gb of ram which is then garbage collected later? Serialization won't show this up either. – rollsch Jul 24 '19 at 05:47
-
-
Compiler says BinaryFormatter is deprecated now. See https://aka.ms/binaryformatter – Veverke Feb 07 '23 at 14:40
I don't think you can get it directly, but there are a few ways to find it indirectly.
One way is to use the GC.GetTotalMemory
method to measure the amount of memory used before and after creating your object. This won't be perfect, but as long as you control the rest of the application you may get the information you are interested in.
Apart from that you can use a profiler to get the information or you could use the profiling api to get the information in code. But that won't be easy to use I think.
See Find out how much memory is being used by an object in C#? for a similar question.

- 153,850
- 22
- 249
- 325

- 35,612
- 10
- 61
- 76
-
11While the "true" answer may be "it can't be done," the better answer is the one that gives you a possible alternative. – Gordon Bean Jan 22 '15 at 19:01
-
This worked well for me. In my case I was working with a very complex object that couldn't really be serialized easily, so the top ans was out of the question. I used this method with a for loop to get a rough average at each point. Helped me see the difference between when this entity didn't exist vs then it did. Delta == rough size of the entity. – mBrice1024 Jul 15 '17 at 14:45
-
Well, sometimes I get a number (which then matches other test runs), sometimes I dont. I just wanted to point that out. (Maybe GC was not finished before running the testapp again? I dont know... ) – Jan Jan 08 '20 at 14:28
Unmanaged object:
Marshal.SizeOf(object yourObj);
Value Types:
sizeof(object val)
Managed object:
- Looks like there is no direct way to get for managed objects, Ref: https://learn.microsoft.com/en-us/archive/blogs/cbrumme/size-of-a-managed-object

- 3,630
- 21
- 39

- 5,469
- 2
- 29
- 43
-
3
-
1It is interesting; I have checked Marshal.SizeOf(
) and it gave me 4... why if bools are size of 1? – Eru Nov 26 '20 at 21:35 -
1I think, there is 1 bit relevant but the framework still using the 4bytes or 8bytes (depending on ur architecture) .... You can read a detailed explanation here https://www.quora.com/In-C-why-is-the-size-of-the-bool-1-byte-Isnt-just-1-bit-enough – Henry Jan 11 '21 at 04:04
OK, this question has been answered and answer accepted but someone asked me to put my answer so there you go.
First of all, it is not possible to say for sure. It is an internal implementation detail and not documented. However, based on the objects included in the other object. Now, how do we calculate the memory requirement for our cached objects?
I had previously touched this subject in this article:
Now, how do we calculate the memory requirement for our cached objects? Well, as most of you would know, Int32 and float are four bytes, double and DateTime 8 bytes, char is actually two bytes (not one byte), and so on. String is a bit more complex, 2*(n+1), where n is the length of the string. For objects, it will depend on their members: just sum up the memory requirement of all its members, remembering all object references are simply 4 byte pointers on a 32 bit box. Now, this is actually not quite true, we have not taken care of the overhead of each object in the heap. I am not sure if you need to be concerned about this, but I suppose, if you will be using lots of small objects, you would have to take the overhead into consideration. Each heap object costs as much as its primitive types, plus four bytes for object references (on a 32 bit machine, although BizTalk runs 32 bit on 64 bit machines as well), plus 4 bytes for the type object pointer, and I think 4 bytes for the sync block index. Why is this additional overhead important? Well, let’s imagine we have a class with two Int32 members; in this case, the memory requirement is 16 bytes and not 8.

- 80,612
- 21
- 160
- 208
-
5This does not answer the question of the OP, how are we supposed to measure the size of a HashSet vs a List? – yoel halb Mar 06 '18 at 16:19
-
@yoelhalb - it does answer, and fairly precisely. There isnt a one-statement or short answer to the question. – StingyJack Jan 27 '19 at 15:09
The following code fragment should return the size in bytes of any object passed to it, so long as it can be serialized. I got this from a colleague at Quixant to resolve a problem of writing to SRAM on a gaming platform. Hope it helps out. Credit and thanks to Carlo Vittuci.
/// <summary>
/// Calculates the lenght in bytes of an object
/// and returns the size
/// </summary>
/// <param name="TestObject"></param>
/// <returns></returns>
private int GetObjectSize(object TestObject)
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
byte[] Array;
bf.Serialize(ms, TestObject);
Array = ms.ToArray();
return Array.Length;
}

- 7,310
- 17
- 40
- 61

- 247
- 2
- 3
-
2Didn't work for me. I didn't have the object class defined as serializable and it threw a "Not marked as serializable error" – dreamerkumar Nov 29 '12 at 20:23
-
2Hi @Kevin Hirst, i tried with this that parsed my dataset to get the size in bytes. Its return me Out of memory exception. I find out that bytes max size is 2 GB ? Have any idea how to manage it? – Worgon Apr 24 '13 at 08:21
-
@Worgon, do you really need to know how big is your dataset except investigational purposes? I'd rather think up a level, to eliminate such a necessity. If you insist, you might think about meausuring of particular datarow size or use abovementioned `GC.GetTotalMemory` approach. – Alexey Khoroshikh May 28 '13 at 07:42
-
@Worgon 2GB is a memory size of .NET environment for your Application. You can't easily mange it - only store big objects in other heap. – VMAtm Jun 06 '14 at 06:49
-
1This is a copy of the most voted answer, which has it's problem, but this code has several issues, first the binaryformatter is slow, but then there is a memory stream without using, then a copy of the data to an array. – NiKiZe Sep 28 '20 at 09:43
In debug mode
load SOS
and execute dumpheap command.
-
9looks like something from windbg, and it could be really useful. Can you elaborate how to do this in Visual Studio? – Arsen Zahray Mar 25 '16 at 22:35
-
2Here's how to do it in visual studio: https://stackoverflow.com/a/66929670/56621 – Alex from Jitbit Apr 03 '21 at 09:47