2

I'd like to know when exactly I should use the Session and when exactly I should use the cache. Are there differences in performance? Can one of them handle a lot of data better? Should the Cache only be used for stuff that's associated with the Application whilst the Session should only be used for stuff that's associated with the current session/user? Is it wiser to save values which I received from a DB in the Session or the Cache - is there a difference at all assuming I make the cache-keys unique? E.g. Cache["MyKey"+UserId.ToString()].

Also, in general, is using the Session/Cache a lot wiser than retrieving Data from a DB or a Webservice or is there a limit of data that'll be retrieved quicker?

Dennis Röttger
  • 1,975
  • 6
  • 32
  • 51

1 Answers1

6

Some differences between session and cache:

  • The session is per user while the cache is per application
  • You can store the session data out-of-process (SessionServer or SqlServer) e.g. when using a web farm
  • What you put into the session stays there until the session is terminated/abandoned or times-out
  • With the cache, you can specify that items are automatically removed after some time (absolute) or after they were not accessed for some time (sliding)
  • You can also use SqlCacheDependencies to have items removed from the cache when some data changes in a database
  • the ASP.NET runtime will also automatically remove items from the cache if the available memory gets low

As for performance:

  • As long as you use InProc session state, I guess there won't be any performance difference between session and cache.
  • As soon as you use external session state, performance will obviously be lower than the InProc-cache but I don't have any numbers (depends on network, SQL server power, etc).
  • BTW: there are also distributed caching solutions which allow having an external, shared cache (similar to the out-of-process session state).
M4N
  • 94,805
  • 45
  • 217
  • 260
  • See also this question: http://stackoverflow.com/questions/428634/cache-v-s-session – M4N May 31 '11 at 08:06
  • Yup, I've seen that question, unfortunately it doesn't really go into the whole performance-part. Do you happen to have any input on that? Session Vs Cache and both of them vs Db/Webservice? Thanks! – Dennis Röttger May 31 '11 at 08:07