Last Updated: February 25, 2016
·
1.148K
· dbgrandi

TMCache performance with large UIImages

TMCache is a great tool, but I recently had some performance issues when caching large images.

My use case was this... I'd get JPGs from our server and cache both the full size image and a scaled down image to disk using the TMDiskCache, which itself uses NSCoding to encode what is persisted to disk.

The problem is that encoding a UIImage uses UIImagePNGRepresentation by default to create the NSData that is persisted for the encoder. So, what started out as a 600KB jpg file, was being cached as a 4MB png representation.

The solution was to create my own NSData and then cache that. In this case, it was creating a JPG representation at 70% compressionQuality.

So, instead of using it like this...

[[[TMCache sharedCache] diskCache] setObject:imageToCache forKey:cacheKey];

try this...

NSData *jpgData = UIImageJPEGRepresentation(imageToCache, 0.7);
[[[TMCache sharedCache] diskCache] setObject:jpgData forKey:cacheKey];

Just remember that you have to re-create your image when you pull it out of the cache later on.

NSData *jpgData = (NSData *)[[[TMCache sharedCache] diskCache] objectForKey:cacheKey];
UIImage *image = [UIImage imageWithData:jpgData];

(NOTE: These are illustrative, you are probably better off using the async methods.)

This cut the disk usage by a significant amount, which helped keep the TMDiskCache serial queue free for work.

It's not a good solution for every case. But, for large pictures that don't need pixel perfect reproduction, it's nice.