My app uses 95MB of ram, when I made investigation by instruments I found out that CoreUI Image Date uses 70MB, how to reduce that usage?
-
Are you loading a large image file? Multiple images at once?– Daniel StormAug 8, 2015 at 12:23
-
Nope, just the image.xcassets and they're 12 images with 2MB size.– Tareq El-MasriAug 8, 2015 at 12:27
-
How big are the images though? I takes 4 bytes per pixel to load an image from file into RAM.– nhgrifAug 8, 2015 at 13:11
-
12 image with 2MB size– Tareq El-MasriAug 8, 2015 at 13:13
-
1The question is the dimensions of the images, not the file size of the assets. Images are generally compressed, but are uncompressed when used in the app. For example, a random photo on my device takes 1.5mb, but when uncompressed, it requires over 30mb. Bottom line, the memory used at runtime is often 4 times width times height, which will greatly exceed the amount of space used by the original JPG or PNG file.– RobAug 8, 2015 at 13:25
1 Answer
There are a few considerations:
The only image objects that should be instantiated are those that are currently on screen. Do not hold the images in an array. (You might use a cache for performance reasons, but purge that cache upon memory pressure.) Sure, have an array of image file names (or identifiers or what have you), but not of the images, themselves.
For example, you want to ensure that you dynamically instantiate the images as they're needed (e.g. as they scroll into view) and release them when they are longer visible (e.g. as they scroll out of view).
If the dimensions of the images exceed the dimensions of the image views (adjusted for the scale of the display), these images should be resized to match. The amount of memory consumed is a function of the dimensions of the image, not of the image view. For example, a 100x100 image will take 40kb, but a 1000x1000 image will take 4mb.
These two points are relevant because images often require far more memory than might be suggested by the file size of the original assets. The runtime memory usage is a function of the image dimensions, not the file size of the assets. Image files are generally compressed, but are uncompressed when used by the app. The memory used at runtime is often 4 times width times height of the image, which will greatly exceed the amount of space used by the original JPG or PNG file.
-
hey Rob. I am making a game where user can unlock items as they gain points. There are 150 + 125 x 125 images and I was wondering how to add them? They will appear in a UICollectionView which is embeded in a UIViewController. Should i put them in the assets or something like imgix.com ? Thank you!– brkrMay 31, 2016 at 21:45
-
1
-
1I know this is a old answer. But what about using a NSCache? He could store the images in a NSCache and it will automatically purge the cache of images if a memory warning is triggered. Jun 24, 2016 at 11:33