IOS App performance optimization

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

 

IOS App performance optimization

Performance of iOS App

Although the function of iPhone is getting better and better, but the function of app is more and more complex, the performance is always one of the core concerns of mobile development. We say that an app performance is good, not easy to feel run faster, but refers to the application of quick start, UI feedback timely response, scroll the list of smooth operation, memory usage, reasonable, and certainly not casually Crash. Engineers to develop application in addition to appear in the design to avoid performance "pit", in practice, "pit" to the fast positioning reasons. Causes of performance problems cannot be guessed location, reasonable method is to use the tool measuring evaluation of the highest return on investment issues, and then to be further optimized.

This paper will analysis from the following points is introduced and the optimization of iOS performance of app: the start time, the user response, memory, graphics and animation, file and network I/O. The performance analysis of Apple will be used by the artifact"Instruments".

Start time

The user experience for the first time critical application startup time, at the same time system on the application startup, restore state run time also has strict requirements, application in case of a timeout will close the application system. The following is the requirement for the app run time of several common scenarios system: * Launch 20 seconds Resume 10 seconds for 10 seconds Suspend Quit Background Task 10 minutes 6 seconds

To the time required to obtain accurate app start, first add the following code in the main.c method is the most simple time:

1
2
3
CFAbsoluteTime StartTime;
int main(int argc, char **argv) {
  StartTime = CFAbsoluteTimeGetCurrent();

Then add in the application:didFinishLaunchingWithOptions callback method in AppDelegate:

dispatch_async(dispatch_get_main_queue(), ^{
    NSLog(@"Lauched in %f seconds.",  (CFAbsoluteTimeGetCurrent() – StartTime)); 
});You might think why can get the system up time, Because the submit this work in dispatch_async will run in the app main thread after the start of the next run lopp, At this time app has finished loading and will display the first frame, That is before the system will run to `-[UIApplication _reportAppLaunchFinished]`. Below is the Instruments tool Time Profiler ran the call stack, recommend the use of Instruments method and performance WWDC [session Video] (), to write the word too thin is not intuitive. 

From the picture we can see the completion of the system call application:didFinishLaunchingWithOptions before the [UIApplication system call _reportAppLaunchFinished].

App startup will include the following components (from WWDC 2012 to Session 235):

1)Link and load: can display dyld loadable library functions in Time Profile, library will be mapped into the address space, at the same time bound and static initialization.

2)UIKit initialization: if Root View Controller is realized by XIB, will also be initialized at boot time.

3)Application: call the UIApplicationDeleagte callback callback: application:didFinishLaunchingWithOptions

4)The first Core Animation calls: call in method after the start of the -[UIApplication _resportAppLaunchFinished] CA:: Transaction:: commit rendering the first frame. If your program got off to a slow start, can do is to first and show the execution after the first screen independent operation in the; if you are using XIB files in the load the first screen, the View layer in the XIB file will be if flat, not too many layers.

User response

How to let users find your app rapid response? Of course is to trigger the app user operation can be immediately in response to user events, namely (User Event) to be the main thread run loop timely treatment. What is run loop? Select multiplexing can be imagined as a processing event. The main thread of run loop of course is mainly to process user generated events, such as click, scroll. Later we will talk in detail run loop this confusing.

To make in response to user events of the main thread run loop better, engineers should minimize the main thread to do hard work time, especially reading file ah, network operation, a lot of operation. This kind of hard work, if a blocking operation, it is taboo. We can use multiple threads (NSThread, NSOperationQueue, GCD, a Blog will talk to this multi thread) can bring out the main thread, which belongs to the explicit concurrency. There are kinds of implicit concurrency, such as view and layer animation, layer rendering and PNG picture decoding are performed in another sub thread. In addition to the use of multi threading technology to reduce the burden of the main thread, the main thread occlusion in reduced but also enhance the user experience of a method. Use the Time Profiler tool Instruments in Recod thread "waiting" option to each thread blocking system calls the app runtime information statistics, For example, the file read and write read/write, Network read and write send/recv, Locking psynch_mutex_wait etc. Instruments System Trace tools are able to record all of the underlying system call.

Memory

Memory has been a long-standing problem iOS app, cannot do well program will burst. Because the iOS system without the Swap file (know why not leave suspense?), The memory will be read-only data (e.g. code page) out from memory, When you need to read from the disk such as memory; read and write data will not be removed from the memory system, However, if the memory reaches a threshold, The system will issue a corresponding notification and callback allows applications to the release object to reclaim memory, If you still cannot reduce memory usage, The system will close the application. Especially iOS 5, if your app received memory warning, then the head is the same as other app on the chopping board, at any time may be kill off, not to say will be first Kill away in the background of app.

The memory used by App in addition to our allocated on the heap memory (+[NSobject alloc]/malloc), with more memory use place also, such as code and global data(TEXT andDATA), Thread stack, pictures, view layer backing store etc.. It is not only a memory problem, we developed app to minimize the application memory so simple.

There is now a stunning ARC, memory problems is relatively less, the development efficiency is improved. But many companies still due to historical reasons using manual memory management, the work done or not. Static analysis with the Xcode can help you find some problems ahead of time, however, some memory problems is unable to use static analysis to find, as we continue to use the memory not timely release problem, the analysis cannot use a static analyzer. At this point you can use the Instruments Allocations and Leaks tools to check the runtime memory usage and leak problem.

The Allocations tool can be very intuitive reaction app memory usage, there is a great "Mark Heap" function, in the Heapshot Analysis part of the above left in. For example, you enter a page before clicking on "Mark Heap", and then to return to the previous page by clicking on "Mark Heap", if you import for the page of memory has been a reasonable release, then the heap memory growth rate should fall to 0 (see chart right part).

Another serious problem is the memory references have been freed, directly lead to the application of collapse, marked and Allocation has an option Enable NSZombie detection was able to release in the use of memory, at the same time display the call stack information error. This provides the most direct help to solve the problem, of course, is must be able to reproduce the EXEC_BAD_ACCESS error.

Tool Leaks can directly indicate a memory leak code in application run time, if there is a memory leak, concrete objects can be leaked details from the view leakage and method invocation stack, most of the problem is very good solve.

Graphics and animation

Graphics performance has a direct impact on the user experience, Instruments Core Animation tool for graphics performance measurement of physical machine, the refresh frequency size view to judge the performance of graphics applications. For example, a complex scroll the list when it's refresh rate should try to close to 60fps to make the user feel is smooth, from this figure can also calculate the longest response time of run loop should be 16 milliseconds.

Start Instruments Core Animation tool can be found in left lower part has a lot of options, we introduce:

1) Color Blended Layers

Instruments can be demonstrated by mixed layer in the Blended Layer on the physical machine (marked in red), Blended Layer because the Layer is transparent(Transparent), The system requires the view and lower view mixed in rendering these view (Blend) to calculate the actual color of the pixel, If the blended layer a lot, Then in the scrolling list do not want to have smooth effect.

To solve the blended layer problem is also very simple, The opaque property to check the red region view, Remember to check the backgroundColor property set to YES; Is it right?[UIColor clearColor], To know the background color to clear color but that the graphics performance, The basic means that blended layer is run, Why? They think:)

2) Color Hits Green and Misses Red

Many view Layer as rendering of Shadow, Mask and Gradient etc. the reason is high, Therefore, UIKit provides API to cache the Layer: [layer setShouldRasterize:YES], The system will be the Layer cache into Bitmap bitmap for rendering using, If the failure will discard these re generate Bitmap. The Rasterization layer grid benefits is to refresh rate are less affected, the downside is that grid processed Bitmap cache memory, and when the layer to China ", to do additional calculations on the grid after Bitmap. Using this option, if the Rasterized Layer fails, will be marked as red, if effectively marked green. When testing the application frequently flashed red labeling layer, Rasterization layer showed little effect on the.

3) Color Misaligned Images

Misaligned Image said to draw points cannot be mapped directly to the pixel frequency screen, the system needs the pixels of adjacent anti-aliasing anti aliasing calculation, increase the burden of the graphics, usually resulting from re calculation and setting in the View Frame.

Pictured above are marked as yellow layer, which is due to the layer is the scaled image, if these pictures are downloaded from the Internet, you can program update in order to determine the drawing size to solve. Also some systems Navigation Bar and Tool Bar of the background image is using the tensile (Streched) images, can also be expressed as yellow, this is normal, usually without modification. This problem on the performance impact is not big, but may be in the edge of Grammaticalization.

(4) Color Offscreen-Rendered Yellow

Offscreen-Rendering off screen rendering means iOS to display a view, Need to first in the background is calculated using CPU view Bitmap, To do Onscreen-Rendering display on the screen for GPU, Because the display a view requires two computation, So this Offscreen-Rendering will lead to the decline of APP graphics performance.

Most of the Offscreen-Rendering are and view Layer Shadow and Mask, the following conditions will lead to view Offscreen-Rendering: 1 using Core Graphics (CG at the beginning of class). 2 uses the drawRect () method, even if it is empty. 3 shouldRasterize CALayer attribute set to YES. 4 using CALayer setMasksToBounds (masks) and setShadow* (shadow) method. 5 directly on the screen to display text, including Core Text. 6 set UIViewGroupOpacity.

This blog Designing for iOS: Graphics & Performance offsreen and graphics performance have a great introduction, (5) Color Copied Images Copied Image options can be labeled by Core Animation mapping application copy pictures, Marked a blue green. Although I met at run time, but personally feel little effect on graphics performance. (6) Color Immediately, Flash Updated Regions, Color OpenGL Fast Path Blue Color Immediately option disables the 10 ms Instruments in color-flush operation delay. The Flash Updated Regions option for the red shows marked on the screen using GPU calculation and drawing layer. Color OpenGL Fast Path Blue option is used to mark the drawing by OpenGL compositor in the contents of the screen in blue. The three option analysis significance to the graphics performance of small, usually only as a reference.

File and network I/O

If you do the analysis of APP file and network I/O needs, can be used in the three Instruments System Usage, File Activity and Network.

System Usage can be applied statistics under the running state of files and network operation data for IO. For example, we found another peak after starting the application, there may be a problem, we can use the information bar System Usage tool to view the application is due to what file read and write operations to the peak.

File Activity can only run in the simulator, so the data acquisition may not be very accurate. It also details read file attributes, size, loading time and other information, suitable for use in conjunction with the System Usage.

Network tools can be collected using information using TCP/IP and UDP (the amount of data transmission, all current TCP connection), with not much, do the analysis of network usage when using.

Read more

Knowledge related to iOS many App performance, it is just the tip of the iceberg, recommended WWDC session.

WWDC 2012:

WWDC 2011:

There are several good blog:

http://oleb.net/blog/2011/11/ios5-tech-talk-michael-jurewitz-on-performance-measurement/

http://eng.pulse.me/tips-for-improving-performance-of-your-ios-application/

http://robots.thoughtbot.com/post/36591648724/designing-for-ios-graphics-performance

http://www.touchwonders.com/en/how-to-make-your-apps-feel-responsive-and-fast-part-2/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Otis at February 26, 2014 - 8:40 PM