Friday, February 17, 2012

Size of a DataTable in a Session

Storing an object in the session for easy access by other pages is the easiest way to move around objects in a web application but
What’s the size of a DataTable stored in a session
I used serialization as shown here http://stackoverflow.com/questions/1689045/can-i-get-the-size-of-a-session-object-in-bytes-in-c
After creating a DataTable with a few columns and 100 rows,
like...
        private DataTable getTable()
        {
            #region make tables         
            //        Add around 10 columns to the table
            #endregion
            for (int i = 0; i < 100; i++)
            {
                dt.Rows.Add(...//add 10 rows
                dt.AcceptChanges();
            }
            return dt;
        }
After putting it to a session I tried calculating the memory using...

protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                long totalSessionBytes;
                BinaryFormatter b = new BinaryFormatter();
                MemoryStream m = new MemoryStream();
                DataTable dt = getTable();
                Session.Add("tab", dt);
                b.Serialize(m, Session["tab"]);
                totalSessionBytes = m.Length;
                Response.Write("Total MB = " + (totalSessionBytes/1000).ToString());

            }
        }


Then It showed 137 MB! And even when Session is replaced with ViewState, it gave the same result. 137! Well… So I saved the binary object to a file Making the DataTable in a constructor of a class, and serializing it...

    [Serializable]
    public class serialtest
    {

        private DataTable dt = new DataTable();


        public serialtest()
        {
            dt = getTable();
        }
     
        private DataTable getTable()
        {
              //the method above
        }
    }


Then making the object and serializing it to a file
private void makefile(serialtest s)
        {
            Stream str = File.OpenWrite("C:\\ serial.txt");
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(str, s);
            str.Close();

        }


The size of the file, it said 240KB I did the same thing with a ViewState and the result was exactly the same So, there is no conclusion as to how you will be able to get the size of the object in a viewstate or a session

No comments:

Post a Comment