iOS Performance optimized memory management: Analyze, Leaks, allocations use and case code

Source: Internet
Author: User

Recently took a small task, and the company's iOS partners to share the specific use of instruments, so with this blog ... Performance optimization is a big topic, and the main discussion here is the memory leaks section.

I. Some related concepts

A lot of people should know more about this piece of content ... Can right when review review ...

1. Partition of memory space: We know that a process occupies a memory space, contains 5 different data regions: (1) BSS segment: Usually holds uninitialized global variables, (2) data segment: Usually holds initialized global variables. (3) Code snippet: Typically, the code that holds the program executes. (4) Heap: Typically used to store memory segments that are dynamically allocated during a process run , andOC objects (all objects that inherit from NSObject) are stored in the heap. (5) Stack: The compiler automatically allocates the release, storing the function parameter value, local variable equivalent.

Stack memory is managed by the system, so we often say that memory management refers to the management of heap memory, that is, the creation and destruction of all OC objects. With the advent of iOS5, Apple has introduced arc (automatic reference counting) technology, in this mode the compiler will automatically insert retain, release, autorelease statements in the appropriate place, that is, the compiler will automatically generate memory management code, the liberation of the vast number of programs ape hands, It also basically avoids the memory leak problem, but ...

2. Memory leak: Baidu Encyclopedia to give the definition is: "Memory leak is also known as ' storage leakage ', with dynamic storage allocation function dynamically opened up space, after the use has not been released, the result has been occupied in the deposit element. Until the end of the program. (In fact, it is not recycled after the memory space is used) is called a memory leak. Memory leaks in iOS apps, for reasons such as circular referencing, strong/copy, and so on.

Two. analyze-Static analysis

As the name implies, static analysis does not need to run the program, you can check where there is a memory leak.

1. How to use: Open Xcode,command + SHIFT + B; or xcode-product-analyze;

2. Three common types of leaks:

(1) An object was created, but not used. Xcode hint message:Value Stored to ' number ' is never read. Translation: The value stored in ' number ' has never been read.

(2) A (pointer-mutable) object is created and initialized, but the initialized value has not been read. Xcode hint message:Value Stored to ' str ' during it initialization is never read

(3) A function that has an object reference count plus 1 is called, but the function that makes its reference count minus 1 is not called. Xcode Tip info:Potential leak of an object stored into ' subimageref '. Translation: The memory unit of the Subimageref object has a potential risk of exposure.

3. Paste the Demo code:

/** Scenario One: An object was created, but not used. * Hint message: value Stored to ' number ' is never read * Translate: Values stored in ' # ' have never been read,*/- (void) Leakone {nsstring*STR1 = [NSStringstring]; NSNumber*Number ; number=@ (str1.length); /*say we have not read it, then read it, such as open the following code, send it a class message, there is no longer a hint.     Of course, the best way is to delete the code about number, because, you only assign a value, and do not use, then why create it. This is a more common and typical error, and it's easy to check it out*/    //[number class];}/** * Scenario Two: A (pointer-mutable) object is created and initialized, but the initialized value has not been read. * Hint message: Value Stored to ' str ' during it initialization is never read*/- (void) leaktwo {nsstring*STR = [NSStringstring];//Create and initialize STR, at which point there is already a memory unit that holds the value of the STR initialization//nsstring *str;//This will not reveal the memory, because STR is mutable, only need to declare the line first. //printf ("str ago =%p\n", str);str =@"Ceshi";//Str was changed, pointing to the address where "Ceshi" was located, the pointer changed, but the memory space where the initialization value was saved was not released, and the memory unit that saved the STR initialization value was compromised. //printf ("str after =%p\n", str);//the pointer changed.[Strclass]; //give two more examples, the sameNsarray*arr =[Nsarray array]; //printf ("Arr ago =%p\n", arr); //Nsarray *arr; //so that the memory does not leakarr = @[@"1",@"2"]; //printf ("arr =%p\n", arr);//the pointer changed.[Arrclass]; CGRect rect=Self.view.frame; //CGRect rect = Cgrectzero;//so that the memory does not leakRect = CGRectMake (0,0,0,0); NSLog (@"rect =%@", Nsstringfromcgrect (rect));}/** * Scenario three: Call a function that lets an object reference count plus 1, but does not call the corresponding function to let its reference count minus 1. * Tip: Potential leak of an object stored into ' subimageref ' * Translate: The memory unit of the Subimageref object has a potential risk of compromise*/- (void) leakthree {cgrect rect= CGRectMake (0,0, -, -); UIImage*image; Cgimageref Subimageref= Cgimagecreatewithimageinrect (image. Cgimage, rect);//Subimageref reference count + 1;UIImage* Smallimage =[UIImage Imagewithcgimage:subimageref]; //The corresponding function should be called, so that the reference count of Subimageref minus 1, it will not disclose the//cgimagerelease (subimageref);[Smallimageclass]; Uigraphicsendimagecontext ();}
View Code

Post photos:

Three. leaks-memory leaks

Leaks is a dynamic memory leak checking tool that needs to run a program while testing.

1. How to use: Enter Xcode,command + control + i; or Xcode-xcode-open Developer tool-instruments; or xcode-product -profile. Select Leaks.

2. Interface details as follows, this is the interface of the runtime

Several projects have been tested, and it is found that the memory leaks are less than the code checked with static analysis. There are 2 items can point the button is point, can enter the page is in, leaks also did not detect leakage.

Four. allocations-memory allocation

Allocations is the memory allocation in the process of testing the program, it also needs to run the program at the same time. 1. Open method: Ibid. 2. The interface situation is as follows:

Two:

Double-click on a method, the same will jump to the code, there will be each code corresponding memory allocation, according to this information, you can have a program in the memory of the different code to understand, and targeted optimization.

Five. Some tips for writing code in peacetime

At the end of the day,instruments is just a set of tools that help us analyze the code, the memory problems and performance issues that might be examined, and certainly the code. To develop good code habits is the fundamental solution. The first is to avoid the three common memory leaks that are mentioned in static analysis, which I have seen in several of the projects I have tested.

TIP1: What will increase the memory usage of the app? "Non-full version"

(1) Create the object and define the variable. (2) Call a function or method.

TIP2: What conditions increase CPU consumption? "Blog from the author of Yykit (highly recommended):ibireme"

(1) Create objects, adjust object properties, destroy objects. (2) Layout calculation and AutoLayout. (3) Calculation and rendering of text. (4) Decoding and drawing of pictures. "With time Profiler, it's more intuitive to feel what's taking longer and how to use it." "

Summary: Do a good job of reusable objects such as cell reuse; You can create objects once, do not create multiple times (such as a function popup for a page), implement functionality with fewer object and method calls, and put time-consuming operations on child threads to optimize memory and performance .

iOS Performance optimized memory management: Analyze, Leaks, allocations use and case code

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.