iOS Advanced Tutorial: Handling Memory optimizations for 1000 images

Source: Internet
Author: User

First, the project needs

In the actual project, when the user uploads the picture, sometimes will upload a large number of pictures at once. Before uploading the image, we need to do a series of operations, such as: Rotate the picture in the correct direction, compress the picture, etc., these operations need to load the picture into memory, the following on the use of memory to do a detailed analysis.

Second, memory analysis, non-optimization

In my test project, I repeated loading a picture 1000 times, first loading the image into memory, then compressing, freeing the memory

12345678910111213141516171819 for (int i = 0; i <= 1000; i ++) {       //1.首先我们获取到需要处理的图片资源的路径        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"PNG"];        //2.将图片加载到内存中,我们使用了alloc关键字,在使用完后,可以手动快速释放掉内存        UIImage *image = [[UIImage alloc] initWithContentsOfFile:filePath];       //3.这一步我们将图片进行了压缩,并得到一个autorelease类型实例        UIImage *image2 = [image imageByScalingAndCroppingForSize:CGSizeMake(480, 320)];       //4.释放掉2步骤的内存        [image release];    }

The above code does not seem to have any problem, can be said to be a standard code notation, in each step of the memory is handled with care, we look at the actual memory usage:

As can be seen in our operation without any problems, when loading a large number of images, it will still cause memory loss.

When you can see that memory is automatically freed, the memory occupied by the picture is not immediately released

These resources do not immediately release resources, consume valuable memory resources, and eventually kill the program.

Three-optimized memory usage

The above program was killed because of the memory usage of the program, in the above code, we each step of the memory has been very careful processing, but when loading a large number of images, there will still be problems. The root cause is autorelease, Autorelease automatically frees up memory and does not immediately release the memory, but waits until the next event cycle is released. The problem is that some resources we have to use the autorelease type, such as the return value of the function, and most of the system APIs and projects are doing the same, and if all depends on our manual release it is easy to cause a memory leak.

12345678910111213141516171819 for (int i = 0; i <= 1000; i ++) {       //创建一个自动释放池        NSAutoreleasePool *pool = [NSAutoreleasePool new];        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"PNG"];        UIImage *image = [[UIImage alloc] initWithContentsOfFile:filePath];        UIImage *image2 = [image imageByScalingAndCroppingForSize:CGSizeMake(480, 320)];        [image release];       //将自动释放池内存释放,它会同时释放掉上面代码中产生的临时变量image2        [pool drain];    }

Optimized, Memory usage

Free memory is no longer significantly reduced

Cgimage and UIImage data from the original 220 to reduce to 6-7

You can see that when NSAutoreleasePool is used, there is no memory problem when loading a large number of images.

Iv. Overview of the automatic release pool

(1) The auto-release pool is placed on a stack, although they are often referred to as being "nested". When you create a new auto-free pool, it is added to the top of the stack. When the auto-free pool is reclaimed, they are removed from the stack. When an object receives a send Autorelease message, it is added to the current thread's auto-free pool at the top of the stack. You cannot send autorelease or retain messages to the auto-free pool. Application kit will start at the beginning of an event cycle (or event loop iteration)-such as a mouse down event-to automatically create an auto-free pool and release it at the end of the event cycle, so your code usually doesn't have to care. There are three scenarios in which you should use your own automatic release pool:

    • If you are writing a program that is not based on application kit, such as a command-line tool, there is no built-in support for the auto-free pool; You must create them yourself.

    • If you generate a dependent thread, you must immediately create your own auto-free pool Once the thread starts executing, otherwise you will leak the object.

    • If you write a loop that creates a number of temporary objects, you can create an auto-free pool inside the loop to destroy them before the next iteration
      Object. This can help reduce your application's maximum memory footprint.

(2) Differences between release and drain

In the reference count environment, release and drain, like, will automatically free the pool L object directly.

In a GC (garbage collected) environment, release is a no-op (empty operation), and drain triggers garbage collection (if the memory allocated since the last garbage collection is greater than the current threshold).

Typically, you should use drain instead of release to destroy the auto-free pool.

The-drain method is only available for Mac OS X10.4 (Tiger) and later versions.

Under OS X Mountain Lion v10.8 operating system, GC (garbage collection) will be discarded, ARC (Automatic Reference counting Auto Reference count) is the recommended alternative.

iOS Advanced Tutorial: Handling Memory optimizations for 1000 images

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.