Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best usage of NSCache across an app

I'm wondering if it's best to use one global instance of NSCache, or several ones for each component that need it.

For example, I have several view subclasses that draw content into images and cache them to avoid regenerating them all the time. Is it better to have one instance of NSCache per class, or just 1 centralized NSCache for the whole app?

Note that I don't mean one cache per instance of an object, it's retarded to do that. I'm talking about one instance of NSCache for each class.

like image 357
Olivier Avatar asked Dec 05 '12 16:12

Olivier


People also ask

When to use NSCache?

You typically use NSCache objects to temporarily store objects with transient data that are expensive to create. Reusing these objects can provide performance benefits, because their values do not have to be recalculated. However, the objects are not critical to the application and can be discarded if memory is tight.

What is an efficient way to cache data in memory in Swift?

Avoiding stale data What makes NSCache a better fit for caching values compared to the collections found in the Swift standard library (such as Dictionary ) is that it'll automatically evict objects when the system is running low on memory — which in turn enables our app itself to remain in memory for longer.

Is NSCache persistent?

NSCache is really nice for a few reasons: It stores data in memory only. If our app gets killed, this memory is freed up and it's not persisted to disk. The key-value pair mechanism lets us very easily set and get cached content.


2 Answers

It obviously depends, but I would generally vote for one cache for each type of cached object. That way, you can have different countLimit values for each, e.g. to specify things like "keep the 50 most recently rendered thumbnails", "keep the 5 most recently downloaded large images", "keep the 10 most recently downloaded PDFs", etc.

For really computationally expensive tasks, I also employ two tier caching, NSCache for optimal performance, and saving to a temporary/cache directory in the local file system to avoid costly download cycles while not consuming RAM.

like image 177
Rob Avatar answered Sep 28 '22 21:09

Rob


If cached items might be shared across components, you might as well have a unified cache - lookups won't be significantly more expensive and you at least have a chance of reducing redundant copies of your cached objects.

But if the cached items are unique per component, mixing them in a cache is pointless and from a code readability perspective likely confusing. Keep the caches separate, in that case. That also lets you more precisely control them - e.g. you could evict more aggressively in caches from components not being immediately used.

like image 39
Wade Tregaskis Avatar answered Sep 28 '22 21:09

Wade Tregaskis