iphoneobjective-ciosnscache

Use a global NSCache or one per class?


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.


Solution

  • 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.