简体   繁体   中英

Suitable method to implement caching in asp.net

I need to implement caching in Asp.net web application My need to store data with different ID's. So which method is better ?

  1. Use a dictionary variable. Insert the data (key as ID and data as value).

      Dim mDict As New Dictionary(Of String, String) mDict .Add(bID, uwtTree.WriteXmlString(True, True)) Cache.Insert("mTree", mDict) 

    Add it to a cache variable. Access the cache variable

      If Not Cache("mTree") is Nothing Then 'cast to dictionary and check ID exists , if exsitis get the data End iF 
  2. Use cache variable for different IDs

      Cache.Insert(ID,data) ' each insertion for each ID If Not Cache(ID) is Nothing Then ' get the data. ' End IF 

Which method is the best way ? Or is there any other method exists ? I am using .Net 3.5 /IIS 7 (VB.Net). Thanks in advance

Way to Improve Performance and Memory Optimization

Without context it's not possible to say which is "better".

But if you put a dictionary in the cache (option 1), better make sure it's a thread-safe dictionary (such as the .NET 4 ConcurrentDictionary).

The most obvious difference between the two approaches is that with option 1, cache item expiry will result in the dictionary with all items being removed at once. With option 2, individual items will expire independently.

In response to the comment:

i am having xml data and i will store in cache (data caching) as string. Is there any difference if i store it as XmlObject ?

The main differences I see are:

  • String is immutable, so you won't need to worry about thread-safety when accessing it. XML objects are not immutable - so you need to make sure you don't modify the object retrieved from the cache (or use locks to make sure any such modification is thread-safe).

  • If you store a string, you will presumably parse it into an XML object each time you retrieve it from the cache, which will result in a potential performance penalty.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM