From the doc
Add(CacheItem, CacheItemPolicy) : When overridden in a derived class, tries to insert a cache entry into the cache as a CacheItem instance, and adds details about how the entry should be evicted. [1]
-
Set(CacheItem, CacheItemPolicy) : When overridden in a derived class, inserts the cache entry into the cache as a CacheItem instance, specifying information about how the entry will be evicted. [2]
I see little difference in the wording (tries to) and signature (set
is a sub, add
returns a boolean), but I'm not sure which one I should use and if there is really something different between both.
Object caching is a process that stores database query results in order to quickly bring them back up next time they are needed. The cached object will be served promptly from the cache rather than sending multiple requests to a database. This is more efficient and reduces massive unnecessary loads on your server.
Caching enables you to store data in memory for rapid access. When the data is accessed again, applications can get the data from the cache instead of retrieving it from the original source. This can improve performance and scalability.
The Main difference is that the Add()
method tries to insert a cache without overwriting an existing cache entry with the same key.
While the Set()
method will overwrite an existing cache entry having the same key. [ However If the key for an item does not exist, insertion will be done as a new cache entry ].
Above was the difference in terms of their functionality.
Syntactical Difference:
One significant syntactical difference is that the Add()
method returns a Boolean which is true
if insertion succeeded, or false
if there is already an entry in the cache that has the same key as item. The Set()
method has a void
return type.
One last point that internal implementation of Add()
method actually calls its corresponding version of AddOrGetExisting()
method.
public virtual bool Add(CacheItem item, CacheItemPolicy policy) { return this.AddOrGetExisting(item, policy) == null; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With