How to optimize the memory usage and program size of the cocos2d program: Part 1

Source: Internet
Author: User
ArticleDirectory
    • What consumes 90% of the memory?

Translator:

When I completed my first game project, I was deeply aware that "developers who use cocos2d to create games are mostly troubled by cocos2d memory problems ". When I first got started with cocos2d,CommunityPeople in the article discussed a very meaningful topic: "Please briefly describe what you think cocos2d programmers should first know before coding, or what they should pay attention." There are many answers to this question: "How to load and store game data" and "how to implement a finite state machine. One of the most attractive ones is that cocos2d, a newbie.ProgramThe 80% problems they encounter are related to memory.

 

I agree with the C/C ++ background when I saw this sentence, so I paid special attention to the memory problems when I started cocos2d programming. Even so, when I completed my first game, I still encountered a lot of memory problems, which gave me a headache and made me sleep. Fortunately, I found the answer through the Community and solved my problem.

 

I have also talked about some memory usage experiences in my blog post "My first foodiethebug. However, it is not specific enough. I wanted to talk a lot about it. Some of them are difficult to use text to make things concrete, and I am also a little lazy. This time, when I seeSteffen itterheimAfter I wrote two articles about cocos2d memory optimization and program size, I felt like I had a feeling of "feeling at ease. I can't wait to share it with you. Unfortunately, many people complain that they can't access the website, and they will be attacked. There may also be some colleagues who are not very popular with e-Wen. During the weekend, I spent an afternoon translating and sharing with you.

 

The full text is as follows:

I am currently finishing my last contract project. One thing I need to consider at the end of this project is how to optimize the memory usage of the game.

 

In today's idevblogaday article, I will tell you how I can reduce the memory consumption of 25-30 mb of the game (now the game consumes 90-95 MB of memory, and through this process, eliminates program crashes caused by memory warnings ). At the same time, I also reduced the size of the game program from 25 MB to less than 20 MB (if Apple did not recently raise the limit for downloading apps from 20 mb to 50 MB, so my small optimization will be great, and it will potentially bring me more downloads ).

I will also introduce how to display an animated loading interface when loading game resources. I will also add some best practices and tips.

 

What consumes 90% of the memory?

Let's guess :)

In most cases, texture (textures) consumes a lot of memory for the game program. Therefore, texture is the first object to be optimized, especially when you encounter a memory warning problem.

 

Avoid loading PNG and jpg textures one by one (wait for at least one frame between them)

Texture loading in cocos2d is divided into two phases: 1. Create a uiimage object from the image file. 2. Create a cctexture2d object using the created uiimage object. This means that when a texture is loaded, it will consume two times the memory size occupied by it in a short time. Why is it just a short time? Because of the relationship between autorelease pool and reference count, the newly created uiimage object will be recycled .)

When you load four textures one by one in a method body, the memory problem becomes worse. Before this method ends, each texture consumes two times its memory.

I'm not sure whether cocos2d is still like this. Or is this only applicable to manual reference counting management, maybe not for arc? I am used to loading textures in order, but I have to wait for a frame before loading the next texture. This will reduce the memory pressure caused by the consumption of any texture loading. If you wait for one frame, the reference count will release the temporary uiimage object to reduce the memory pressure. In addition, you can also use this method in subsequent articles if you want to load textures in sequence in the background thread.

 

Do not use JPG images!

There is a problem when using JPG textures for cocos2d-iphone. When a JPG texture is loaded, it is converted to a PNG texture in real time. This means that cocos2d-iphone loading textures is very slow (as shown here), and jpg textures consume three times the size of memory occupied by themselves.

A 2048*2048 texture consumes 16 MB of memory. When you load it, it will consume 32 MB of memory in a short time. Now, if the image is in JPG format, you will see that the number will reach 48 MB because of the creation of additional uiimage objects. Although the memory will eventually be reduced to 16 MB, the memory usage at that time will be high enough for the OS to kill your game process, cause crash, and affect the user experience.

JPG is poor in both loading speed and memory consumption. Therefore, do not use JPG!

 

Ignore file image size

I have seen many such cases. It may seem a bit absurd at first glance, but the truth is that it requires knowledge about file formats, which not every programmer knows. What I often hear is "Hey! My program cannot have memory warning. All my image resources add up to less than 30 mb !".

What should I do? Because the image file size and texture memory usage are two different things. Suppose they are tents. The picture file is equivalent to the tent being packed in the suitcase. However, if you want to use a tent, it must be held up and expanded ".

The relationship between image files and textures is similar. Most of the image files are compressed. If they are used, they must be decompressed before they can be processed by the GPU and become a well-known texture. A 2048*2048 PNG image, with 32-bit color depth encoding, occupies only 2 MB space on the disk. However, if it becomes a texture, it will consume 16 MB of memory!

Of course, there is a way to reduce the memory size occupied by textures.

 

Use 16-bit texture

The fastest way to reduce the memory usage of textures is to load them as 16-bit color-depth textures. The default texture pixel format of cocos2d is 32-bit color depth. If the color depth is halved, the memory consumption can be halved. In addition, this will increase the rendering efficiency by about 10%.

You can use the cctexture2d object class method setdefaultalphapixelformat to change the default texture pixel format,CodeAs follows:

 
[Cctexture2d setdefaultalphapixelformat: kcctexture2dpixelformat_rgb5a1]; [[cctexturecache sharedtexturecache] addimage: @ "ui.png"];

 

There is a problem: first, the change in the texture pixel format will affect all the textures loaded later. Therefore, if you want to use different pixel formats for subsequent texture loading, you must call this method and re-set the pixel format.

Second, if the pixel format you set in cctexture2d does not match the pixel format of the image itself, the display will be severely distorted. For example, the color is incorrect, or the transparency is incorrect.

 

What are some useful texture pixel formats?
Generate 32-bit textures: kcctexture2dpixelformat_rgba8888 (default) generate 16-bit textures: bytes 16-bit textures: bytes 16-bit textures: bytes (no alpha)

 

Rgba8888 is the default format. For a 16-bit texture, rgb565 can be used to obtain the optimal color quality, because the 16-bit texture is used to display the color: A total of 65536 Of the total color values. However, there is a disadvantage here, unless the image is rectangular and there is no transparent pixel. Therefore, the rbg565 format is suitable for background images and user controls with some rectangles.

The rbg5a1 format uses a color to represent the alpha channel, so the image can have a transparent area. However, it seems that one digit is not enough. It can only represent 32768 available color values. In addition, images can only be transparent pixels, or all are not transparent pixels. Because of the alpha channel, there is no median. However, you can use the fade in/out action to change the opacity attribute of the texture.

If your image contains a translucent area, the rbga4444 format is very useful. It allows 127 Alpha values for each pixel value, so the transparency efficiency is not very different from the texture of rgba8888 format. However, because the total color quantity is reduced to 4096, rbga4444 is the worst color quality in 16-bit image formats.

Now you can get a 16-bit texture deficiency: due to the decrease in the total color, some images may be distorted and may generate a "gradient ".

 

Make 16-bit textures look better

Fortunately, we have texturepacker. (TP)

TP has a feature called "jitter", which can improve the distortion problem originally caused by a decrease in the number of colors. (There is a lot of jitter in TPAlgorithmFor more information about these algorithms, see another article I translated ).

Especially with the pixel density displayed by retina, you can hardly see the display difference between 16-bit and 32-bit textures. Of course, the premise is that you need to adopt the "jitter" algorithm.

The default color depth of cocos2d will render all textures to the 16-bit color framebuffer and then display them on your device screen. In this case, why don't we convert all texture formats into 16 bits? What is the use of 32 bits? It will be rendered to a 16-bit framebuffer. This problem is a bit too low-level. I don't want to dig deep into it, and I am not suitable to explain it. (TRANSLATOR: Haha, knowing is knowing, not knowing)

 

Use npot texture

Nopt is short for "non power of two". It is translated as "not a power of 2 ". Npot stands for "non power of two ". in cocos2d1. you must go to ccconfig. npot support is enabled in the hfile, but cocos2d 2. X is not needed. It supports npot by default. All IOS settings after the 3-generation (iPhone 3gs) Support cocos2d 2.x( because they support OpenGL es2.0), so they also support npot textures.

If the texture atlas uses the npot texture, it has a major advantage: it allows TP to better compress the texture. Therefore, we will waste less space in the texture Gallery. In addition, such a texture will use about 1% to 49% less memory during loading. In addition, you can use TP to forcibly generate npot textures. (You only need to check "Allow free size)

Why care about npot? Because Apple's OpenGL driver has a bug, if pot texture is used, an additional 33% of memory consumption will be generated.

 

Texture in PVR format is used by default.

TP allows you to create PVR-format textures. Apart from PVR textures that support npot, they can not only be a power of 2, but also be square.

PVR is the most flexible texture file format. In addition to standard uncompressed RGB image formats, the pvrtc format for lossy compression is supported. In addition, the memory consumption of uncompressed PVR-format textures is very low. Unlike PNG images, which consume 2 times the memory occupied by their own memory, PVR format only consumes the memory size of the texture and adds a little bit of memory size for processing the image format.

One disadvantage of PVR format is that you cannot open it on Mac. However, if you have installed TP, you can use the PVR image browser that comes with TP to browse PVR images. (It is strongly recommended that you purchase TP to support Tp and stop piracy)

Files in PVR format have almost no disadvantages. In addition, it can greatly increase the loading speed, which will be explained later.

 

Use PVR. CCZ File Format

Among the three optional PVR file formats, the PVR. CCZ format is preferred. It is specially designed for cocos2d and TP. In TP, this is the smallest PVR file it generates. In addition, the PVR. CCZ format is faster than any other file format.

When the PVR format texture is used in cocos2d, only the PVR. CCZ format is used. Do not use other formats! Because it is extremely fast to load and uses less memory for loading!

 

Pvrtc compression can be considered when the vision is invisible.

PVR textures support pvrtc texture compression format. It mainly adopts lossy compression. If you compare the pvrtc image with the jpg image, it only has medium quality. However, the biggest advantage is that you do not need to decompress the texture in the memory.

Here we compare the 32-bit PNG Image (left side) with the pvrtc4 (4-bit) image of the optimal quality (click the image to view the full size:

Note that there are obvious flaws in some high-contrast areas. The color gradient looks a little better.

Pvrtc is definitely not the texture format most games want. However, they are very useful for particle effects. Because small particles are constantly moving, rotating, and scaling, it is hard for you to see some visual flaws.

 

Pvrtc compressed image format

The PVR format provided by TP includes not only the above two formats, but also TC2 and tc4.

Here, the Alpha is the same as the Alpha of the 16-bit texture. If there is no alpha channel, there are no transparent pixels in the image. However, more color bits are used to represent the color, so the color quality looks better.

Sometimes, the pvrtc image format uses four or two color values, but not exactly. The pvrtc image format can encode more color values.

 

Preload all textures

As the title says, do your best to load all textures in advance. If all your textures add up to 80 MB memory consumption (it refers to devices with Retina Display, rather than halving the Retina Display ), you can load all the data in the first loading scenario.

The biggest benefit of this is that your game experience will be smooth, and you don't have to worry about resource loading and uninstallation issues.

This also allows you to use the appropriate texture pixel format for each texture, and you can easily find other memory problems unrelated to the texture. If it is related to the texture, this problem will be exposed when all textures are loaded for the first time. If all the textures are loaded and memory problems occur again, it is definitely irrelevant to the texture, but it is another problem.

If you know that the problem is irrelevant to the texture, it will be easier to find the remaining memory problems. In addition, you have avoided the preceding situation: When a 2048*2048 texture is loaded, it only consumes 16 MB of memory, but will rush to 32 MB of memory in a short time. We will propose a method to solve the problem of "Intermittent High memory usage" ("Translator's invention. (Translator: I hope that the "Intermittent High memory" statement will appear in the next developer conversation)

 

Load the texture in the order of texture size from large to small

Due to the extra memory consumption during texture loading, It is a best practice to load textures in a large to small manner by texture size.

Assume that you have a texture that occupies 16 MB of memory and four textures that occupy 4 MB of memory. If you first load a 4 MB texture, this program will use 16 MB of memory, and when it loads the fourth texture, it will soar to 20 mb in a short time. At this time, you need to load the 16 MB texture, and the memory will immediately soar to 48 MB (4*4 + 16*2 ), then it is reduced to 32 MB (4*4 + 16 ).

However, in turn, you first load the 16 MB texture and then compress to 32 MB in a short time. Then it is reduced to 16 Mb. At this time, you load the remaining 4 4 MB in sequence. At this time, the maximum size will be (4*3 + 4*2 + 16 = 36) MB.

In these two cases, the peak memory usage is different from 12 Mb, you know, it may be that these 12 Mb will interrupt your game process!

 

Avoid clearing the cache when receiving the memory warning message

Sometimes I see a strange behavior of "shooting my own feet by myself": All the textures have been loaded in the loading scenario. At this time, the memory warning has occurred, then cocos2d releases unused textures from the cache.

It sounds good. All unused textures are released, !...

You just loaded all the textures and haven't entered any scene (all the textures are treated as "UNUSED "), but it is immediately removed from texture cache. However, you need to use them in other scenarios. What should I do? You need to judge whether the texture is loaded. However, when loading, due to the "Intermittent High memory", I immediately received a memory warning and then released it. Then I decided to load it .... My God, this is an endless loop! This also explains why some children's shoes are stuck when the loading scenario is complete.

Now, when I receive a memory warning, what I do is-nothing. The memory warning is still happening, but it is only when the program starts loading. I know why, because "intermittent memory usage is high", so I don't care about it. (However, if you receive a memory warning during the game process, you should pay attention to it, because at this time you may have memory leakage !!!)

Sometimes I try to improve it by removing unused textures and images that can only be used in special scenarios (such as the settings interface, players are not frequently accessed ). Then, whenever I need an image, I will first check whether the sprite frame is in the cache. If not, load the sprite frame. You will see the specific practices later.

 

Understand when and where to clear the cache

Do not randomly clear the cache. You can also release some memory to Remove unused textures. That is not a good code design. Sometimes, it will even increase the number of loads, and trigger "Intermittent High memory" for multiple times ". Analyze the memory usage of your program to see what exists in the memory and what should be cleared, and then only clear the cleanup.

You can use the dumpcachedtextureinfo method to observe which textures are cached:

 
[[Cctexturecache sharedtexturecache] dumpcachedtextureinfo];

 

The output of this method is as follows: (for clarity, I have blocked the information related to the-HD suffix)

Cocos2d: "ingamescorefont.png" rc = 9 namedomainingamescorefont-hd.png id = 13 128x64 @ 32 bpp => 32 kbcocos2d: "ui.png" rc = 15 name‑ui-hd.png id = 5 2048x2048 @ 16 bpp => 8192 kbcocos2d: "ui-ingame.png" rc = 36 name‑ui-ingame-hd.png id = 8 1024x1024 @ 16 bpp => 2048 kbcocos2d: "digits.png" rc = 13 name‑digits-hd.png id = 10 512x64 @ 16 bpp => 64 kbcocos2d: "hilfe.png" rc = 27 name‑hilfe-hd.png id = 6 1024x2048 @ 32 bpp => 8192 kbcocos2d: "settings.png" rc = 8 name1_settings-hd.png id = 9 1024x1024 @ 16 bpp => 2048 kbcocos2d: "blitz_kurz.png" rc = 1 name = (null) id = 12 50x50 @ 32 bpp => 9 kbcocos2d: "gameover.png" rc = 8 name1_gameover-hd.png id = 7 1024x2048 @ 32 bpp => 8192 kbcocos2d: "home.png" rc = 32 name‑home-hd.png id = 4 2048x2048 @ 16 bpp => 8192 kbcocos2d: "maid" rc = 2 name = (null) id = 11 87X65 @ 32 bpp => 22 kbcocos2d: "stern.png" rc = 2 name = (null) id = 2 87x65 @ 32 bpp => 22 kbcocos2d: "clownmenu.png" rc = 60 name1_clownmenu-hd.png id = 1 1024x2048 @ 32 bpp => 8192 kbcocos2d: cctexturecache dumpdebuginfo: 13 textures using 60.1 MB (total texture memory size !!!)

It contains a lot of useful information. The size, color depth (BPP), and memory usage of each cached texture. The "RC" here represents the "reference count" of the texture ". If the reference count is equal to 1 or 2, it means that this texture may not need to be used now. At this time, you can safely remove it from the texture cache.

You only remove the textures that you know are unlikely to be used in the current scenario (that is, the reference count described above is 1 or 2). This is a wise practice. In addition, only the textures that occupy large memory are removed. If a texture occupies only a few KB of memory, it does not affect other operations. This is the same as program optimization. Do not optimize too many details, do not optimize too early, locate performance bottlenecks, and then focus on optimization, exchange 20% of the time for 80% efficiency. Too early and too much detail optimization needs to be avoided for most programs ).

 

Spriteframes retain textures!

In the above example, the reference count of the texture may be a bit confusing. You will find that the texture set has a high retain count, even if you know that the textures in these texture sets are not currently used.

You may have ignored one thing: ccsprteframe retests its texture. Therefore, if you use a texture set, it is not that easy to completely remove it. Because the sprite frame generated by this texture set is still stored in the memory. Therefore, you must call the removespriteframecache removespriteframesfromtexture method of ccspriteframesfromtexture to completely clear the texture set in the texture cache. Note: instead of calling the object's release method, the object's memory will be released, but the reference count will be 0, so that the memory will be deleted)

 
[[Ccspriteframecache sharedspriteframecache] removespriteframesfromtexture: uncachedtexture];

You can also use removespriteframesfromfile and specify a. plist file of the texture set to clear cached spriteframes ).

 

 

Adding spriteframes is time-consuming!

Note:This is only effective for cocos2d V1.0, and cocos2d v2.x is pre-determined before being loaded.

This seems a bit ignorant (innocent ):

 
[[Ccspriteframecache sharedspriteframecache] addspriteframeswithfile: @ "UI. plist"];

However, please note that ccspriteframecache does not check whether a Sprite frame has been cached! This is different from the Action Method of cctexturecache. It loads spriteframes each time.

How long does this process take? It depends on the number of Sprite frames in the. plist file you provide. I noticed that only 14 frames of plist loading is very different from 280 frames of plist loading. Therefore, you also need to be cautious when loading sprite frames.

Therefore, you must avoid unnecessary addspriteframes * method calls. This causes a small lag During scenario switching.

 

You can clear any cache (such as animation and sprite frames), but do not clear the texture cache easily.

Cocos2d has many caching classes, such as texture caching, Genie frame caching, and animation caching. However, if you want to clean up the memory, the sprite frame cache and animation cache occupy a very small amount of memory.

Of course, if you want to remove a texture from the memory, you must also remove the relevant sprite frame (because the sprite will retain the texture ). To put it bluntly, do not easily remove the sprite frame and animation cache, because you may use an animation frame object or Sprite frame object that is not cached, which will lead to program crash.

 

Exception: Check the memory usage of audio files!

Audio files are cached and can be played repeatedly without being interrupted. As sound files are generally relatively large, I have seen some developers use non-compressed sound files as the background music of the game, and these background music files are very large, they usually cause a large amount of memory consumption.

Use audio files in MP3 format. This is because the use of non-compressed audio files wastes both memory and program size. When you load some game sound effects, remember to uninstall them when you don't need them. In the second article, I will introduce more knowledge about audio files.

 

How to Avoid caching specific textures

What if you do not want to cache a texture? For example, images in the initial loading scenario, or images that users seldom care about-for example, images in your very cool scenario.

It is often overlooked that a texture is displayed and cached. If you move this texture from the cache, then removing the genie will cause the program to crash. This is incorrect.

Cctexturecache only adds a retain function to the texture. In this way, when no other object (such as sprite) holds a texture reference, the texture still exists between memory. Based on this, we can immediately remove the texture from the cache so that the texture will be immediately released from the memory when it is not needed. The following code is used:

BG = [ccsprite spritewithfile: @ "introbg.png"]; // don't cache this texture: [[cctexturecache sharedtexturecache] removetextureforkey: @ "introbg.png"];

Remember, when you remove a texture from cctexturecache, cocos2d calls spritewithfile next time, the texture will be loaded again-whether or not an image with the same name is being used by other genie. Therefore, if you are not careful enough, you may finally Load two duplicate textures in the memory.

One example is that when you load textures in a loop, you do not want to cache these textures. In this case, you need to remove the cache of the texture outside the loop. Otherwise, multiple textures may be repeatedly loaded into the memory:

 

Nsarray * highscores = [Achievements sharedachievements]. highscores; For (highscoredata * Data in highscores) {nsstring * entry = [nsstring stringwithformat: @ "% 05u", Data. score]; cclabelatlas * label = [cclabelatlas labelwithstring: Entry charmapfile: @ "pipizahlen.png" itemwidth: 18 itemheight: 27 startcharmap :'. ']; [labelsnode addchild: Label Z: 10];} // don't hold on to this texture: [[cctexturecache sharedtexturecache] removetextureforkey: @ "pipizahlen.png"];

The above example is taken from the highscore scenario. Once this scenario exits, it should not hold the reference of the cclabelatlas texture. Therefore, we need to remove it from the texture cache. However, you must avoid repeatedly loading textures into the memory.

In this way, we can easily clear the texture in the cache, and it is best to clear the texture when creating it, instead of in other places, for example, dealloc or simply let the purge cache do this.

 

Use a loading scenario

If you cannot pre-load all textures, you can use a loading scenario and display an animation to indicate the loading progress. In this way, you can destroy the previous scenario and release the memory resources it occupies before entering the next scenario.

Implementation is very simple. In this loading scenario, a selector is scheduled and each frame (or 0.1 seconds) executes a function, such as update. Unless Memory leakage occurs in the previous scenario, some memory resources with reference count 0 will be released during each update function execution. In this update method, you can create a new scenario.

This greatly avoids the "Intermittent High memory" problem and can greatly reduce the memory pressure.

 

Load texture in the background

The cctexturecache class also supports asynchronous resource loading by using the addimageasync method. You can add a callback method to the addimageasync method, so that you will be notified when the asynchronous texture loading ends.

This is very important: You must wait for a resource to load. Otherwise, the "Intermittent High memory" may cause the following problems:

1) program crash
2) The texture is loaded twice! Asynchronous loading does not guarantee the Loading Order.

Load other game Resources in the background

However, we have no way to asynchronously load sprite frames and other resources. However, we can use performselectorinbackground to implement similar asynchronous loading functions:

 
[Self defined mselectorinbackground: @ selector (loadspriteframes :) withobject: Nil];

The selector method in receives only one object parameter (but is not used ). Then you can load resources asynchronously in this method, as shown below:

-(Void) loadspriteframes :( ID) object {[ccspriteframecache sharedspriteframecache] addspriteframeswithfile: @ "Hilfe. plist "]; [[ccspriteframecache sharedspriteframecache] addspriteframeswithfile: @" home. plist "]; [[ccspriteframecache sharedspriteframecache] addspriteframeswithfile: @" UI. plist "]; [[ccspriteframecache sharedspriteframecache] addspriteframeswithfile: @" gameover. plist "]; [[ccspriteframecache sharedspriteframecache] addspriteframeswithfile: @" ui-ingame.plist "]; [[ccspriteframecache sharedspriteframecache] Comment: @" settings. plist "]; [[ccspriteframecache sharedspriteframecache] addspriteframeswithfile: @" digits. plist "];}

The biggest benefit of doing so is that when you load resources, you can play animations in the loading scenario, add genie, and run some actions, which can be processed smoothly. This advantage even works well on a single CPU machine, but it works better if your device has multiple CPUs.

However, you must note that you cannot load textures in the background thread. You must use the addimageasync method. This is because the texture must be loaded in the same thread as the common OpenGL context. In this way, you must first asynchronously load the texture and then load sprite frames in the background. You cannot rely on ccspriteframecache to load the texture in the background thread.

 

Load game resources in sequence

The following code is my Asynchronous Method for loading textures and sprite frames (loading in another thread :)

Assume that each frame of the loadassetsthengotomainmenu method is triggered. Assetloadcount and loadingasset variables are declared in the class interface, which are init and bool types:

 

-(Void) increaseassetloadcount {assetloadcount ++; loadingasset = no;}-(void) loadassetsthengotomainmenu :( cctime) Delta {nslog (@ "load assets % I", assetloadcount ); switch (assetloadcount) {Case 0: If (loadingasset = No) {loadingasset = yes; nslog (@ "================ loading home.png ====================== "); [cctexture2d Repository: Repository]; [[cctexturecache sharedtexturecache] addimageasync: @ "home.png" target: Self selector: @ selector (increaseassetloadcount)];} break; Case 1: if (loadingasset = No) {loadingasset = yes; [self defined mselectorinbackground: @ selector (loadspriteframes :) withobject: Nil];} break; // extend with more sequentially numbered cases, as needed // The default case runs last, loads the next scene default: {[self unscheduleallselectors]; mainmenuscene * mainmenuscene = [mainmenuscene node]; [ccdirector shareddire] replacescene: mainmenuscene] ;}break ;}}

When this method runs to the first case statement, we set the loadingasset flag to yes to prevent the same image from being loaded multiple times. After the texture is loaded, we add increaseassetloadcount (this quantity can be used to display the progress bar loading percentage ). The subsequent case statements can also load more things, such as sound, font files, particle effects, physical configuration files, and level information. No matter how many things are loaded, the last default statement will be executed, and then you can enter mainmenuscene.

The general purpose of this method is that you can use case and assetloadcount to asynchronously load multiple textures and avoid the "Intermittent High memory" issue. This is because when a method is called every frame, the temporary memory that is loaded with the preceding texture has been released. Because the autorelease pool at the top of the current thread stack will be cleared before each frame is rendered.

 

Note: The content introduced here is for cocos2d-iphone, but the vast majority of content is suitable for cocos2d-x. Therefore, developers can try these methods with confidence. If you have a better way to optimize the memory usage of the game, please share with us. I hope this post will become the ultimate solution to cocos2d memory problems. If you think my translation is good, click the recommendation button next to it. Thanks, enjoy! :)

Happy coding!


How can we reduce the size of game programs? (In the past, the target was below 20 MB, and the current target was below 50 MB. Why? You know !)


And listen to the next decomposition :)

 

Link: http://www.learn-cocos2d.com/2012/11/optimize-memory-usage-bundle-size-cocos2d-app/

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.