Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Graphics caching

When loading images into the app with [UIImage imageNamed: fileName], the system caches the images and therefore provides a performance boost when the same image is used again.

Is there something similar for images created with Core Graphics? I mean images created from contexts with the UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); method.

The current approach I have is to draw the image and save the UIImage to disk, so that next time I need to use the same drawing method I can simply load the cached image from disk. I'm looking for a better way to store Core Graphics generated images as the current approach seems cumbersome.

Maybe even store the CGContextRef with all the drawing in some caching data-structure, I'm not quite sure if that's possible?

My aim is to use only Core Graphics so my app bundle is smaller and I get resolution independence, but I'd like to improve the performance as complicated drawing routines can take a lot of time to process.

UPDATE: After doing some performance testing here are my results. Each time is an average over 100 runs, either drawing 19 or 25 different views at a time. Views included, rectangles, circles, but also text as UILabels. Fills, strokes, gradients and shadows were used.

Caching was implemented as discussed in the answer, with a NSDictionary storing the UIImage objects. Every run had an individual cache, which was used within the run, but not for all the views (out of 25, there were 2 sets of 8, 2 sets of 6 out of 19, which were identical and could be cached).

Here are the times: iOS Simulator

19 views

No caching - average run 11.667ms

Caching - average run 10.321ms

25 views

No caching - average run 14.304ms

Caching - average run 13.509ms

Device

19 views

No caching - average 82.785ms Caching - average 77.831ms

25 views

No caching - average 107.977ms Caching - average 100.094ms

There is a remarkable difference (almost 8%) between the times and when accounting for the longer first time (to save to cache) it would still be beneficial to use the cache.

like image 657
Henri Normak Avatar asked Nov 14 '22 14:11

Henri Normak


1 Answers

I've no performance data to back this up but I think the UIImage caching when using imageNamed is to save reading the file from "disk" and converting the png or whatever to UIImage data.

Therefore your approach of writing to disk would seem to be an unnecessary step - once you have your UIImage object, this is as optimised as you are going to get.

You could consider something like an image "factory" singleton which lazily creates images as they are requested - so the first time, it would do the requisite core graphics operations to create the UIImage, and thereafter return the completed object. Each different image would just be stored as an ivar in your factory.

like image 120
jrturton Avatar answered Nov 16 '22 02:11

jrturton