views:

182

answers:

5

Is it possible to get the size(in bytes) of a Session object after storing something such as a datatable inside it?

I want to get the size of a particular Session object, such as Session["table1"], not the whole Session collection, so the other question, while helpful, is not quite a duplicate.

A: 

Maybe you can use external tools like CLR Profiler or VSTS Profiler to check it.

Michael Pereira
+1  A: 

You could use reflection, see this article.

You might also want to consider having a look at some Memory Performance Counters or perhaps profiling your application with a tool such as DotTrace or the CLR Profiler.

Winston Smith
+5  A: 

You can use marshalling to create a copy of the object, that would give you an approximate number on how much memory it uses.

But, as always it's impossible to give an exact figure of the memory usage. A DataTable object is not a single solid piece of memory that you can measure. It contains a lot of objects and they have references between them, and there may be several references to the same object which means that there isn't one copy of the object for each reference to it. Each DataRow for example has a reference to the table that it belongs to, but that of course doesn't mean that each row has a complete copy of the entire table.

Guffa
A: 

This is taken almost line-for-line from the "duplicate question" from the first comment in the question.

int totalSessionBytes;
BinaryFormatter b = new BinaryFormatter();
MemoryStream m;
b.Serialize(m, Session["table1"]);
totalSessionBytes = m.Length;
Dan Herbert
Serialisation adds a lot of metadata though, which is included in the size.
Guffa
I agree. It's not easy to get the size of an object programmatically. The method I gave is a rough estimate at best, and extremely over-exaggerated at worst.
Dan Herbert
A: 

YourKit .NET profiler http://www.yourkit.com/dotnet/ shows retained ("deep") size of all objects.

Regards,

--serge

Serge