Memory Usage Investigate of iOS View Render

These days I spent some time investigating how iOS manages memory for view and image rendering. That is, if we draw a view or image on the screen, how much memory will be cost by this operation. I want to know this, because I want to accurately manage(estimate) memory used by our app.
There are two tools we can use to see memory used by one app, one is Activity Monitor provded by Instruments, the other is TOP, which is a useful tool of linux platform. If you want to use TOP to see memory, you have to jailbreak you iPad/iPhone, and install TOP, then you can use ssh to connect to your device and use top.

###Memory used by View Rendering

In one tech session of WWDC 2011, an apple SE mentioned that, if a view override drawRectmethod, then iOS will create an backstore for it. That means for every view who override drawRect, if we add it to the view hierarchy, it will cost view.frame.width * view.frame.height * 4 bytes memory of the system.

###Memory used by Image Rendering
Memory used by image rendering is a little complicated. We need to do two things we draw an image.

  • Stage1:Load image data from net or local disk
  • Stage2:Draw image to view using some kind of draw technique

####Memory used by Loading Image
The total memory used by drawing an image also includes memory used by Stage1 and Stage2. In my app, to load an image, I use the following code:

1
2
3
NSData* imgData = [NSData dataWidthContentsOfFile:imgurl];
UIImage* image = [[UIImage alloc] initWidthData:imgData];
....

With this load technique, Mcmory used is almost [imgData Length] bytes, which is different from memory used by loading image from bundle with code UIImage* image = [UIImage imageNamed:imgName];. You can do a test, if you are interested.

####Memory used by image drawing
There are many techniques to draw an image, I mainly focus on two of them

  • draw image to CALayer with [CALayer setContents] method
  • draw image to a rect with [UIImage drawInRect] method

With the first technique, after we call [mLayer setContents:mImage]', we can see memory is increased byimageWidth imageHeight 4` bytes.

With the second technique, I don’t see any obvious memory growth except memory used by the view that the image is drawn to(I override drawRect method of that view, and call [UIImage drawInRect] there).

If you have any idea how iOS manages rendering memory, welcome to leave me a comment, I am interested in that :).