Use a global NSCache or one per class?
Asked Answered
S

2

7

I'm wondering if it's better 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 one centralized NSCache for the whole app?

I don't mean one cache per instance of an object! I'm talking about one instance of NSCache for each class.

Soucy answered 5/12, 2012 at 16:45 Comment(0)
S
3

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.

Silsbye answered 6/12, 2012 at 9:32 Comment(1)
I like the idea of having different cache rules for each object. And good point for having a centralized object to manage the caches. Save to disk is obviously a good practice.Soucy
D
2

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.

Documentation answered 5/12, 2012 at 17:44 Comment(1)
That's also how I see things. I'd be curious to have more opinions on that topic though.Soucy

© 2022 - 2024 — McMap. All rights reserved.