IOS memory optimization and debugging tips

Source: Internet
Author: User
Tags addchild

Basic section

1: Picture Memory Size Summary

A: Picture: Is the memory of the large, especially mobile game pictures of many resources. The calculation of the memory footprint of picture resources becomes the regular work of J2ME game developers, Cocomo to explain how to calculate the footprint of a picture in memory: memory footprint = width * High * pixel bytes, where the number of pixel bytes varies depending on the model.

For example, the memory footprint of a 64*64 picture on 7210 is =64*64*1.5=6144 (byte) =6k, the amount of memory consumed on S60 =64*64*2=8192 (bytes) =8k. The number of pixel bytes varies depending on the model, for example, 7210 is a 4096 color model, that is, 12 bits to represent a pixel, so multiply 1.5, and S60 is a 65536-color model, with 16 bits to represent a pixel, so multiply by 2.

B:xcode use instruments to view picture memory problems

If you are using an emulator, then the default is a small screen, so the largest picture is 1024 *1024 * 4 = 4 M (1024 is the width of the picture, 4 indicates that the picture's storage type is 4 bytes.) which is RGBA8888)

If you load the picture then you are using 4M of RAM. If you need to render, then you need 4M of RAM.

Loading is usually **load (NSString *) filename,

Rendering is typically node AddChild (node)

2: Reference count problem

Increase in reference count: The A:alloc object refers to an object reference number +1

B: Call retain (detail some examples below)

-> For example you are cocos2d user will see Addchild will make child node reference count +1

->ccarray AddObject also makes the reference count of the element +1

To sum up: all the elements or subnodes added to the binding do not need to be retain, just call release at the time of establishment

Reduced situation: Call Release to make reference count-1 (detail some examples below)

-> Collection Call Remove/removechildbytag, etc. deformed

Call Autorelease when-> is created. Note: If your object is a local object and is created using Autorelease,

So when you leave the method, if you don't have retain then this object will be Dealloc (reference count-1)

Official website of the introduction:

You are own any object to create by allocating memory for it or copying it.

Related Methods:alloc,allocwithzone:,copy,copywithzone:,mutablecopy,mutablecopywithzone:

If you are are not the creator of a object, but want to ensure it stays in memory for your to use, can express an Ownershi P interest in it.

Related Method:retain

If you own a object, either by creating it or expressing a ownership interest, you are the for responsible You no longer need it.

Related Methods:release,autorelease

Conversely, if you are is not the creator of a object and have not expressed a ownership interest, you mustnotrelease it.

3: reference documentation

One, iOS with picture memory

On iOS, the picture is automatically scaled to the N-second size of 2. For example, a picture of 1024*1025, the memory occupied with a picture of 1024*2048 is consistent. The formula for calculating the memory size of a picture is a long * wide *4. The memory occupied by such a 512*512 is 512*512*4 = 1M. Other sizes and so on. (The maximum size supported on Ps:ios is 2048*2048).

, Cocos2d-x's picture caching

Cocos2d-x uses Spritewithfile or spritewithspriteframename when constructing an elf, and cocos2d-x loads the picture into the cache either way. If this is the first time the picture is loaded, the picture is loaded into the cache and then read from the cache. If the cache already exists, it is extracted directly from the cache and is exempt from the loading process.

The caching of pictures is mainly handled by the following two classes: Ccspriteframecache, Cctexturecache

Ccspriteframecache is loaded with a large, tiled image, each of which is just one area of the larger image, which is saved in the plist file. It can be loaded into the area just by the name of the small map.

Cctexturecache is a normal picture cache, all of our directly loaded pictures will be placed by default in this cache, to improve the efficiency of the invocation.

Therefore, the entire picture is loaded into memory each time a picture is loaded, or a mosaic is loaded by plist. If it is not released, it will be occupied all the time.

Third, render memory.

Do not assume that when calculating memory, only the memory loaded into the cache can be computed. Take a picture of 1024*1024 as an example.

Ccsprite *psprite = Ccsprite::spritewithfile ("A.png");

After calling this line of code, you can see it in the leaks tool, adding approximately 4M of memory. and then call

AddChild (Psprite);

At this point, the memory has increased by 4M. That is, a picture, if it needs to be rendered, the memory it occupies will be X2.

Then look at the pictures loaded through the plist, such as the large size of the 2048*2048. Want to load a small picture of one of the 32*32

Ccspriteframecache::sharedspriteframecache ()->addspriteframeswithfile ("B.plist");

At this time the memory increased by 16M (Khan)

Ccsprite *pspriteframe = Ccsprite::spritewithspriteframename ("B1.png");

B.png size is 32*32, think is to add a little bit of memory, but the actual situation is to increase 16M of memory. That is, as long as a portion of it is rendered, the entire picture is loaded together.

But the situation is not so bad, these already rendered pictures, if loaded again, the memory will not continue to rise, such as the addition of 100 b.plist another area, picture memory or a total increase 16+16 = 32M, and will not continue to rise.

Four, Cache release

If the game has a lot of scenes, when switching scenes can be the first scene of the memory release, to prevent the total memory too high.

Cctexturecache::sharedtexturecache ()->removealltextures (); release all loaded pictures so far

Cctexturecache::sharedtexturecache ()->removeunusedtextures (); release the picture with reference count of 1 Cctexturecache:: Sharedtexturecache ()->removetexture (), releasing a picture individually

Ccspriteframecache is similar to the Cctexturecache release method.

It is worth noting that the timing of the release, generally in the switch to release resources when the scene, if from A scene switch to B scene, call the function order for b::init ()---->a::exit ()---->b::onenter () If you use the switching effect, such as ctransitionjumpzoom::transitionwithduration functions, the call order of the function changes to B::init ()---->b::onenter ()---->a::exit () And the second way there will be a moment to stack two of scenes of resources, if not to overdo it, it is likely to crash because of memory crunch.

Sometimes when all resources are forced to be freed, an executing animation is thrown out of reference and an exception is ejected, and Ccactionmanager::sharedmanager ()->removeallactions () can be invoked to resolve.

Five, memory optimization

Optimization of the experience is to try to splice pictures, so that the picture side as long as possible to keep 2 of the n-th side and loaded very full. Note, however, that the logically related picture is packaged in a larger image, and the other is to take into account the distribution of the layers when packing. Because Ccspritebatchnode may be used for rendering efficiency, the images in the same batchnode are at one level, so they must be packaged into different plist according to the hierarchical relationships of each picture. Sometimes memory and efficiency can not be both, only try to balance.

Six, other

Finally attach a memory limit for each generation of iOS devices

Device recommended Memory Maximum memory

Ipad2/iphone4s/iphone4 170-180MB 512MB

Ipad/ipod touch3,4/iphone3gs 40-80MB 256MB

IPod touch1,2/iphone3g/iphone1 25MB 128MB

This recommended memory is just some of the results of a test by some people, the available RAM is not greater than half the maximum memory, if the program exceeds half of the maximum memory, it may be hung up.

In addition, in the leaks to see the simulator and the total memory of the real machine, there will be a large discrepancy. The results in the simulator are closer to reality.

Seven, the leakage of the situation

The main way I ran into memory leaks:

1, the most common is that the application of the reference, and then finally forget to release. Specifically, the use of OC Alloc, retain, copy, new, C malloc, realloc, C + +, and so on, and then no corresponding release, free, delete. This is a one-way leak.

2, retain cycle, for OC This use Count way, there may be retain cycle. Two conditions, one, is a retain b,b and retain a, each other to increase the count, this ring can become a lot of layers, is a->b, b->c, C->d, .... Z->a, of course, if the more intermediate layer, the greater the difficulty of detection. Second, the operation of counting reduction is in dealloc, and Dealloc is called to count to 0. These two conditions add up, causing the count to lock, memory leaks.

Practical Exercises

How do I find a memory leak?

One: Use of tools to find

1, first use the analysis of compilation, Analyze build, see the classification of the memory warning.

This can generally be found in the local variable forgotten release, or interrupted in the middle of the release.

2, then the direct use of instruments leak monitoring.

The memory was applied, and then there was no pointer to the memory, which could be considered leak. This detection is generally detected in this state.

3, through the instruments allocation mark Heap.

Perform repetitive operations, marking memory at the end of each scene. If the operation scene does not leak, the memory increase should be 0. This test detects which objects are incremented between marker points. In addition, it takes more than one mark to be accurate, not mark two times to see a memory increase to find the problem.

In instruments, you can see what objects exist, call history, call stack. It was then roughly certain that the object in that class had leaked out.

Second, the overload method.

Although we know which class is leaking, but sometimes do not know the specific is that there is a problem with the count. My own approach is to overload the retain and release methods, and then add breakpoints, if it's a class that I write myself. In order to monitor where the object was retain, there was no corresponding release.

How do I modify a memory leak?

1, the lack of what to fill. If the release is missing, add the release, and the free one will be added free.

2. Reasonable use of autorelease. Interrupts that are returned to the upper level, or Alloc objects to the release center with return. Recommended use of autorelease.

3. Reasonable use of assign. Retain cycle, the essence is redundant two-way retain. An analogy is to determine which object is the root, which is the branches and leaves do not need to manage the root, just know the root is there. So the attributes of those variables that are purely positional are changed to assign, such as delegate.

Ps:

If the use of instruments is not very clear, you can watch this video https://developer.apple.com/videos/wwdc/2010/?id=311

The game I encountered a very difficult to check the leak here to contribute:

For cocos2d users, if the Ccmenu is used, the Onexsit function in Ccscene is also rewritten to detect some changes from the scene. But forgot to call Super Onexsit.

At this time Ccmenu himself registered an event delegate cannot be released causing Ccmenu to be unable to release. Events are always wrong when loaded into other scenarios. That's what caused it.

The solution is naturally to call Super Onexsit. Because he's released delegate here.

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.