Sunday, September 29, 2013

DataTable or DataSet?

If your need is to deal with a single table than go with Datable rather than Dataset. DataSet is havier than datatable in-terms of memory-size. You can run below code snipet and experience it.
DataTable dt1 = new DataTable();
            dt1.Columns.Add("Col1");
            dt1.Columns.Add("Col2");
            DataRow dr = dt1.NewRow();
            dr["Col1"] = "Hello";
            dr["Col2"] = "World";
            dt1.Rows.Add(dr);

            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            formatter.Serialize(stream, dt1); // dtUsers is a DataTable
            Console.WriteLine("DataTable Size is " + stream.Length.ToString());
            stream.Close();

            DataSet ds = new DataSet();
            ds.Tables.Add(dt1);
            System.IO.MemoryStream stream1 = new System.IO.MemoryStream();
            formatter.Serialize(stream1, ds);
            Console.WriteLine("Dataset Size is " + stream1.Length.ToString());
            stream1.Close();
You can see the output as below and find the memorysize diff.

No comments:

Post a Comment