I'm making an app that uses a large amount of UIImageView's and I am wanting to find out the size of each of the UIImageViews's to try and take a look at the app's memory usage in more detail.
I have played around with Instruments and I can see the amount of memory being alloced by the app but I am wanting a more in depth look at what objects use what memory. For example something like:
UIImageViewOne 10Mb
UIImageViewTwo 8Mb
UIImageViewThree 9Mb
UIImageViewFour 3Mb
Is this possible with Instruments or is there an easier way to view this information?
If you want to determine the amount of memory that will be used by an image, you can look at the cgImage
property (which returns a CGImageRef
) and then supply that as the parameter to bytesPerRow
and multiply that by the height
of the image. So, would look like the following (in Objective-C implementation would use CGImageGetBytesPerRow
and CGImageGetHeight
):
guard let cgImage = image.cgImage else { return }
let bytes = cgImage.bytesPerRow * cgImage.height
This, calculates the size of the pixel buffer used by the image when it is uncompressed and used within the app. Frequently this total is equal to 4 times the width times the height (both measured in pixels). (This is one byte for each of the four channels, red, green, blue, and alpha.) This isn't all of the memory associated with the image, but it accounts for the vast majority of it.
When I ran the above code on my 2,880 × 1,800 pixel image, it reported that it took 20,736,000 bytes (i.e. 19.78 mb).
As you know, if you want to see this in instruments, you can use the allocations tool and then drag within a specific range in the graph and you'll see the objects allocated, but not released, within that time period:
You'll see that for that selected range, the largest allocation was 19.78 mb of a ImageIO_PNG_Data
(or if you used a JPG, you'd see a ImageIO_jpeg_Data
).
Unfortunately, tracking these ImageIO
allocations back to our code is a little more complicated than with most memory allocations, because of the sleight of hand that iOS does during the uncompression. But you can see how this ImageIO
allocation correlates to the calculated pixel buffer size.
(See revision history for rendition for earlier versions of Swift.)