Today I ran into a confusion that whether to use Caching or ViewState. I have a page that postback to itself and displays certain events in the events calendar. Each time on the page load I need to find out that if any new events had been added or not. First I was sending requests to the database but this was not a good idea because database operations on each page load event were costing me a furtune. I turned to caching and solved the problem. But later I realized that since the page is posting back to itself hence making it a perfect candidate for viewstate.
After some thinking I decided to go with caching instead of viewstate. The problem with viewstate is that it stores the information in the hidden fields and hence makes the size of the page larger. If you have lot of data which is to be stored in viewstate than the page execution will be very slow since the page size will be large.
Here is final code which uses Caching to retrieve the data:
if(Cache["Events"] == null)
{
// Binding from the Database
Response.Write("Binding from the Database");
BindData();
}
else
{
Response.Write("Binding from the Cache");
myList = (ArrayList) Cache["Events"];
}
}
private void BindData()
{
Events events = new Events();
myList = events.GetEventsInCalendar();
// Put the list in the Cache
Cache["Events"] = myList;
}
No comments:
Post a Comment