Search code examples
iosxcodememory-managementuiimageview

Why does image in xcode takes up 50x more space during runtime than the actual size


I am writing an iphone application and am using several large images. One of the images is a .png file that takes < 1mb. However, during runtime the debugger says it's taking up 50mb of space. I am placing the image through Interface Builder using a UIImageView object.

The question is, why is it taking up so much memory and is there a way to use the image without taking up so much space?


Solution

  • Marc B's comment is right on the money.

    You've got it backwards. It doesn't take 50x more memory "in Xcode" (in the running program) than "the actual size".

    The file on disk is compressed, and takes a lot less space than the image does in memory. The actual size is the size in memory, and the size on disk is a compressed format for saving, but that can't be drawn to the screen.

    To render an image on screen, it needs to use 3 or 4 bytes per pixel (red, green, blue, and sometimes an alpha channel) with no compression. So, if you have a 1000x1000 pixel image, loading it into memory takes 4 million bytes of memory. If you save that to disk, different file formats use varying levels of compression to save that data. One simple scheme is RLE, run-length-encoding. In that scheme, sequential bytes of the same color are written with a special code (e.g. "save 500 pixels of pure blue here," although unless the image is generated with a paint program, there are rarely large areas of exactly the same color. RLE is all but worthless for photographs or scans.)

    Other compression schemes achieve much higher levels of compression. Some compression schemes are "lossy" (which means the image you get back after compressing then decompressing the image isn't exactly the same as the starting image.) JPEG compression is an example of a lossy scheme. In JPEG compression you can adjust the level of compression. Higher levels of compression yield much smaller files, but the resulting images don't look as good, because the amount of data lost gets larger and larger.

    Regardless of the compression scheme, the graphics hardware needs the full 4-bytes-per-pixel in memory before it can draw it.

    P.S. A pet peeve of mine: Xcode is a development environment (editor, compiler, debugger, linker, etc.) Your image isn't drawn "in Xcode". It is rendered in iOS or Mac OS by a program that you happen to compile using Xcode.

    (So when people talk about why "Xcode" runs their code a certain way, it makes experienced developers cringe, and makes you sound ignorant. I don't intend to be mean - just letting you know.)