ViewState Vs Data Caching
Introduction:
A couple of days ago I ran into a
confusion when I had to decide that whether to use ViewState or Data Caching.
The use of ViewState as well as Data Caching technique would have provided me
with the correct solution. One of the techniques was better than the other and I
had to decide that which one to use. In this article I will discuss when to use
ViewState and when to use Caching.
ViewState:
ViewState is one of the techniques
that Asp.net provides in order to save the data for latter use. The important
fact about the ViewState is that it can only save the values for page level
access. It means if I save something on page_1 using Viewstate I cannot access
it on the page_2 using the same technique. For this reason ViewState is only
used to save the values for the page level access which should be maintained
after post backs.
Whenever we write anything in the
ViewState object a hidden field is created in the html. Let's see a small
example of using viewstate. In this example we will use a TextBox and button. We
will write something in the TextBox and press the button to trigger the postback.
After the post back we will display the value of the TextBox using the ViewState
control.
|
private
void Button1_Click(object
sender, System.EventArgs e)
{
if(ViewState["MyValue"] ==
null)
{
ViewState["MyValue"] = TextBox1.Text;
// Clear the value from the TextBox
TextBox1.Text = "";
}
else
{
// Fill the Textbox with the value from
ViewState
TextBox1.Text = ViewState["MyValue"].ToString();
}
}
|
This is a simple example that shows that how you can use
the view state to save the page level values. If you run this and view the
source of the page you will notice that the hidden filed is automatically
created.
| <input type="hidden" name="__VIEWSTATE"
value="dDwtMTY3MTY4OTI3NDs7Pr AYZq+d1r V++f3rE2ngBQMU9l5h" /> |
The value of the hidden field is encrypted but one who
knows the encryption can easily decrypt it that's why ViewState is not
completely safe. Also the size of your page will increase if you are putting
more and more data in the Viewstate control. If you are storing datatable and
datasets in ViewState than it will take much longer for the page to execute.
Let's see a small example of storing large objects in
the ViewState control.
|
private
void Button2_Click(object
sender, System.EventArgs e)
{
DataSet ds = new DataSet();
Articles article = new
Articles();
ds = article.GetAllArticles();
ViewState["MyArticles"] = ds;
}
|
This is very simple example that I am using to explain
the nightmares of using ViewState control. We are simply making a new dataset
object and populating it with the data which is returned from the GetAllArticles
method. Finally, we are assigning the dataset to the ViewState control. Run this
page and click on the button to write the dataset in the Viewstate and than view
the source of the page. You will see something like this:
|
<input type="hidden" name="__VIEWSTATE"
value="dDwtMTY3MTY4OTI3NDt0PHA8bDxNeUFydGljbGVzOz47bD
xiPEFBRUFBQUQvLy8vL0FRQUFBQUFBQUFBTUFnQUFBRkZUZVhOMFpXMHVSR0YwWV
N3Z1ZtVnljMmx2YmoweExqQXVOVEF3TUM0d0xDQkRkV3gwZFhKbFBXNWxkWFJ5WVd3c
0lGQjFZbXhwWTB0bGVWUnZhMlZ1UFdJM04yRTFZelU yTVRrek5HVXdPRGtGQVFBQUFCTl
RlWE4wWlcwdVJHRjBZUzVFWVhSaFUyVjBBZ0FBQUFsWWJXeFRZMmhsYldFTFdHMXNS
|
And this is just three of the 50-60 lines. So, now you
can think that if you are storing large datasets in the ViewState your page size
will grow dramatically and hence the page execution as well as page loading will
be tremendously slow. For this reason we turn to Data Caching.
Let's see what data caching is all about.
Data Caching:
Caching is one of the coolest features in Asp.net.
Caching enables you to store the expensive data into Cache object and later
retrieve it without doing expensive operations. Data Caching can tremendously
increase performance since each time the data is requested you can turn to the
Cache object rather than going to the database and fetching the result.
You all must be familiar with datagrid paging where you
can display certain number of records in the datagrid control and use the
numeric or next-previous buttons to view the other records. All the records are
fetched for each and every page in the datagrid. Meaning that if you have 40000
records in the database and you are using paging. Each time you click to go to
the next page you retrieve 40000 records. This is way too much performance kill.
That's why for this task we can use Data Caching, let's see how we can use data
caching to make our application more efficient.
|
private
void Button3_Click(object
sender, System.EventArgs e)
{
if(Cache["MyArticles"] ==
null)
{
// Go to the database and fetch the
result in the DataSet
// Assign the dataset to the
Cache object
// Cache["MyArticles"] = ds
}
else
{
// This means that Cache is not empty
and there is data in the cache
// Extract the value of Cache
object to the DataSet
// DataSet ds = (DataSet)
Cache["MyArticles"]
}
}
|
The above example is pretty much simple and as you have
also noticed that the syntax for using Data Caching is very similar to the
ViewState object. By using this technique you will only get the data from the
database if the Cache is empty. And if you see the page source you will not find
any hidden fields since Cache is stored in memory rather than in page source.
Final Thoughts:
When it comes to choosing between ViewState and Caching it all comes down to
what you are doing. ViewState is an ideal candidate if you are planning to save
small values. Mostly values of server controls are saved in ViewState. If you
plan to store large datasets, datatables or collections than data caching is an
excellent candidate.
Attachments:
Project Files: ViewStateVsCaching_Sample.zip