2

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.

Xaisoft
  • 45,655
  • 87
  • 279
  • 432
  • 4
    Duplicate: http://stackoverflow.com/questions/198082/how-to-find-out-size-of-session-in-asp-net-from-web-application – Matthew Jones Nov 06 '09 at 17:21
  • I want to get the size of a particular Session object such as Session["table1"], not the whole Session Collection? – Xaisoft Nov 06 '09 at 17:29

4 Answers4

5

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
  • 687,336
  • 108
  • 737
  • 1,005
1

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
  • 21,585
  • 10
  • 60
  • 75
0

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

Michael Pereira
  • 1,263
  • 1
  • 17
  • 28
0

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;
Community
  • 1
  • 1
Dan Herbert
  • 99,428
  • 48
  • 189
  • 219
  • 1
    Serialisation adds a lot of metadata though, which is included in the size. – Guffa Nov 06 '09 at 17:44
  • 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 Nov 06 '09 at 18:01