spentak
spentak

Reputation: 4747

iOS Image View performance enhancement suggestions

My app takes screenshots. I have a main screen with a scroll view that lets you cycle through those snapshots. The problem is, the more snapshots I have, the slower that view runs. I can get about 15 snapshots in the scrollview before things get seriously laggy. The images i'm displaying are only 1/3 the size of the actual screenshot. Each screenshot is an UIImageView on a scrollview. Any thoughts on increasing performance here?

Upvotes: 1

Views: 511

Answers (1)

Ajeet Pratap Maurya
Ajeet Pratap Maurya

Reputation: 4254

The best thing which you can do is to do lazy loading. Only load the images that are visible at that time on that view. Once you scroll the older images get released and the new one gets loaded.

Two ways to load images:

[UIImage imageNamed:fullFileName] // caches the image

or:

NSString *fileLocation = [[NSBundle mainBundle] pathForResource:fileName ofType:extension];
NSData *imageData = [NSData dataWithContentsOfFile:fileLocation];
[UIImage imageWithData:imageData];

or, finally:

[UIImage imageWithContentsOfFile:path] // does not cache the image

Which solution is best depends on what you're doing with the image. The imageNamed: method does cache the image, but in many cases that's going to help with memory use. For example, if you load an image 10 times to display along with some text in a table view, UIImage will only keep a single representation of that image in memory instead of allocating 10 separate objects. On the other hand, if you have a very large image and you're not re-using it, you might want to load the image from a data object to make sure it's removed from memory when you're done.

If you don't have any huge images, I wouldn't worry about caching, so long as you're using lazy loading. Unless you see a problem, I would choose less lines of code over negligible memory improvements.

Upvotes: 5

Related Questions