Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between "Set" and "Add" for ObjectCache?

Tags:

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.

like image 793
Kraz Avatar asked Dec 12 '13 16:12

Kraz


People also ask

What is Objectcache?

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.

What is the caching in c#?

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.


1 Answers

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; } 
like image 94
R.C Avatar answered Sep 18 '22 21:09

R.C