When is it worthwhile to cache UIImage resources?
I've been doing a lot of iPhone UI work with image files that are used in multiple locations in a single view or in several views throughout the application. In some cases, I'm drawing new icons, usually by compositing 2 small images (each less than 4 KB).
I've thought a bit about optimizing the loading of images, but I'm not sure what the best practices would be. I would guess that it would be worthwhile to save any images that are created or altered using CG functions. With images that aren't altered, what is the overhead of 开发者_如何学Pythonloading images from a bundle?
UIImage* image = [UIImage imageNamed:@"myImage.png"]
With the memory constraints of a mobile device in mind, what factors are most important when considering caching images? The size of the image, the total number of images that may be cached, and the number of times a single image is loaded come to mind.
In the latest performance sessions at WWDC (2011), Apple didn't recommend caching images for most cases. They recommend that you only cache images when you know for a fact, after a performance analysis, that you need to cache images ahead of time because you can't afford the time to load them off disk and decode them. In most cases you probably can afford it.
They specifically noted, as @Till does, that +[UIImage imageNamed:]
caches images for the lifetime of your process, and so they recommend using a non-caching loading method, such as +[UIImage imageWithContentsOfFile:]
The reason is that memory is a constrained resource on iOS devices, so if you cache your images, you are likely to cause memory pressure on the system, and apps to get jetsammed. And since iOS 5 jetsams apps using more memory first, if you're caching a bunch of UIImages you're going to make it more likely for your app to get jetsammed.
精彩评论