Reputation: 7877
I have to store data of thousand of records in a data table and maintained on postback. Which option is suitable for me viewstate(which i used) or session. When i used viewstate it will created hidden field for storing it and slow down the page loading. So is there any overhead (server side memory consumption and delay in the responses) in storing it in session. Please suggest me the solution
Upvotes: 8
Views: 15137
Reputation: 383
For large amounts of data, Session is way more efficient. If you can detect when the user is done with a particular block of data, set the Session variable to null, to help memory overhead. You can't always do this, but the Session will eventually expire and the memory will be reclaimed then. Lowering the Session timeout can help some, but don't set it too small, you don't want to cut off your users. Session needs to be enabled in your Web.config file.
Here's the basic guidelines for Session vs. ViewState:
ViewState: The binary data structure of the ViewState is Base64 encoded to be placed into the page, which means it is 1.3333 times (8/6) the size of the original binary data. This data is uploaded and downloaded for each page view. So if you have a lot in the ViewState it impacts page response times. Base64 encoding is probably highly optimized, so that's not a performance hit. Each page request will allocate, then free up, the space for the ViewState, so it's not a long term memory hit. Since the data is in the page, it doesn't expire.
Session: All of the data in the Session is preserved in the web server between page loads. This keeps the page small, it only has to carry the Session identifier. On the down side, any memory used to store data in the Session stays allocated until the Session expires. I've wondered if the Session copies binary data or just keeps a pointer. Like Base64 encoding, this can be highly optimized, so if it happens it is not a performance hit. The Session may expire, if the user waits too long between page views. If the session expires, it should return the user back to some known state in the web page.
One other issue here, if you're storing information in the Session, the session id may be shared among multiple tabs in the client browser. You have to be careful how you're using the data stored in the Session. Make sure you test for this so your users don't get unexpected results.
(Note: Using ViewState is RESTful, Session is not.)
Upvotes: 13