IOS App Performance Optimization

Source: Internet
Author: User
Tags uikit

Performance concerns for IOS apps

While the iphone is getting better, its functionality is becoming more complex, and performance has always been one of the core concerns of mobile development. We say an app performance is good, not simply refers to the feeling of running fast, but should be the application starts quickly, the UI feedback response timely, the list scrolling operation is smooth, the memory use is reasonable, of course, not casually crash. Engineers in the development of applications in addition to the design to avoid performance "pit", in the actual encounter "pit" should also be able to quickly locate the reason. Positioning performance Problems The reason is, of course, impossible to guess, and the logical approach is to use tool measurements to assess the most rewarding problem points and then optimize them.

This article describes how to analyze and optimize the performance of your iOS app: startup time, user response, memory, graphics animation, file, and network I/O. It uses Apple's performance analysis artifact "Instruments".

Start time

The application startup time is very important for the first experience of the user, while the system has strict requirements on the running time of the application startup and recovery, and the system shuts down the application directly when the application time-out. Here are a few common scenarios in which the system requires app uptime: * Launch 20 seconds Resume 10 seconds Suspend 10 seconds Quit 6 seconds Background Task 10 minutes

The simplest way to get an accurate app startup time is to first add the following code to the MAIN.C:

123 
CfabsolutetimeStartTime;IntMain(Intargcchar **argv{ starttime = cfabsolutetimegetcurrent ();   

application:didfinishlaunchingwithoptions added:

dispatch_async(dispatch_get_main_queue(), ^{    NSLog(@”Lauched in %f seconds.”,  (CFAbsoluteTimeGetCurrent() – StartTime)); });可能你会觉得为什么这样可拿到系统启动的时间,因为这个dispatch_async中提交的工作会在app主线程启动后的下一个run lopp中运行,此时app已经完成了载入并且将要显示第一帧画面,也就是系统会运行到`-[UIApplication _reportAppLaunchFinished]`之前。是用Instruments工具Time Profiler跑的调用栈,Instruments的使用方法建议看WWDC中与performance相关的[session录像](https://developer.apple.com/videos/wwdc),文字写起来太单薄不够直观哈。

We can see that the [UIApplication _reportAppLaunchFinished] system callback was completed before the system call application:didFinishLaunchingWithOptions .

The launch of the app will include the following sections (from WWDC Session 235):

1) Linking and loading: You can display the Dyld in time profile, the library is mapped to the address space, and the bindings and static initialization are completed.

2) Uikit initialization: If the app's root View controller is implemented by Xib, it will also be initialized at startup.

3) Application callback: Call Uiapplicationdeleagte callback: application:didfinishlaunchingwithoptions

4) First Core animation call: The -[UIApplication _resportAppLaunchFinished] first frame drawing is invoked in the boot-up method CA::Transaction::commit . If your program starts very slowly, the first thing you can do is to put the action that is not related to the display of the first screen to execute afterwards; If you load the first screen with the Xib file, the view layer in the Xib file should be flat, not too many layers.

User response

How can you make users feel that your app is responding quickly? Of course, the actions triggered by the app user can be immediately responded to, that is, the user event can be processed by the main thread's run loop in a timely manner. What is a run loop? You can imagine a select multiplexing that handles events. The run loop in the main thread is, of course, primarily designed to handle user-generated events, such as clicking, scrolling, and so on. In the future, we'll talk about the confusing stuff of run loop.

To make the main thread's run loop better respond to user events, the engineer should minimize the time of the main thread dry work, especially read the file Ah, network operation Ah, a lot of computing ah this kind of heavy work, if it is blocking operation, it is taboo. We can use multi-threaded (Nsthread, Nsoperationqueue, GCD, the next blog will talk about this multi-threaded) will be hard to move out of the main thread, which is explicit concurrency. There is also implicit concurrency, such as the animation of the view and layer, the drawing of the layer, and the decoding of the PNG image, which is performed in another sub-thread. In addition to using multithreading techniques to reduce the burden on the main thread, reducing blocking in the main thread is also a way to improve the user experience. Use the "Recod thread waiting" option in the time Profiler tool in instruments to count the blocking system calls in various threads of the app runtime, such as file read/write read/write, network read and write Send/recv, Locking psynch_mutex_wait and so on. The system Trace tool in instruments is capable of recording all underlying system calls.

Memory

Memory problems have always been a persistent problem with iOS apps, and the program has exploded. Because the iOS system does not have swap files (know why not?) Left out of suspense), the read-only data (such as code page) is removed from memory when it is out of memory, read as memory from disk when needed, and the read-write data is not removed from memory by the system, but if the memory used reaches a threshold value, The system sends out appropriate notifications and callbacks to apply the release object to reclaim memory, and if it still does not reduce memory usage, the system shuts down the app directly. Especially after iOS 5.0, if your app receives memory warning, then the brain is placed on the chopping board like any other app, and is likely to be killed at any time, not to say that it will kill the app in the background first.

The app uses memory in addition to the memory we allocate on the heap ( +[NSobject alloc]/malloc ), there are more places to use memory, such as code and global data (text and data), line stacks, images, view layer backing store, and so on. So dealing with memory problems is not simply about applying as little memory as possible when we're developing apps.

Now with the super-dazzle arc, the memory problem is much less, and the development efficiency has been improved. But many of the company's projects still use manual memory management for historical reasons, and the job to do is to do so. The static analysis feature from Xcode can help you to identify some problems in advance, but some memory problems cannot be found with static analysis, such as the problem that we are constantly using memory not released in time, we cannot use static analyzer to analyze it. You can use instruments's allocations and leaks tools to check the memory usage and leak issues at run time.

The Allocations tool is a very intuitive response to the memory usage of the app, and there's a great "Mark Heap" feature in the Heapshot analysis in the lower left half. For example, if you click on the "Mark Heap" in front of a page and then go back to the previous page and click on "Mark Heap", the memory growth of the heap should be reduced to 0 if the memory you apply for in and out of the page is properly released (see lower right).

Another serious memory usage problem is referencing the memory that has already been freed, directly causing the app to crash, and allocation has an option to enable Nszombie detection to be annotated when the app uses the memory that has already been freed, and to display the call stack information that occurred incorrectly. This provides the most direct help to solve the problem, but the drawback is that you must be able to reproduce the exec_bad_access error.

The tool leaks can directly indicate the memory leak code when the app is running, and if a memory leak occurs, you can view the specific object and the method call stack from the disclosure details, most of which are well resolved.

Graphics and animations

Graphical performance has a direct impact on the user experience, and the core animation tool in instruments is used to measure the graphics performance on a physical machine and to determine the graphics performance of the application by the size of the refresh frequency of the view. For example, when a complex list is scrolled, its refresh rate should try to approach 60fps to make the user feel fluent, and from this figure it can be calculated that the longest response time of the run loop should be 16 milliseconds.

After starting the instruments Core Animation tool, you can see that the lower left section has a bunch of options, which we'll cover individually:

1) Color blended Layers

Instruments can display the blended layers blended layer (labeled in red) on the physical machine, blended layer is because they are transparent (Transparent), The system needs to mix the view and the lower view when rendering these view (blend) to calculate the actual color of the pixel, if the blended layer is many, then you can scroll the list without a smooth effect.

To solve the blended layer problem is also very simple, check the red area view of the opaque property, remember to set to Yes, check the BackgroundColor property [UIColor clearColor] is not, to know the background color is clear color that is the enemy of graphics performance, Basically means that the blended layer is not going to run, why? Think for yourself:)

2) Color Hits Green and Misses Red

Many view layers are rendered very high for reasons such as shadow, mask, and gradient, so Uikit provides an API to cache these Layer:[layer Setshouldrasterize:yes], These layers are cached as bitmap bitmaps for rendering use, and if they are invalidated, they are discarded bitmap regenerated. The benefit of layer rasterization rasterization is that it has less impact on refresh rates, and the downside is that the bitmap cache requires memory to be erased, and when the layer needs to be scaled, additional calculations are made to the bitmap after the deletion. When this option is used, if the layer of the rasterized is invalidated, it will be labeled red if it is effectively labeled green. When the application of the test flashes a red callout layer frequently, it indicates that the rasterization effect on the layer does little.

3) Color misaligned Images

Misaligned image indicates that the points to be drawn cannot be mapped directly to pixels on the frequency screen, and the system needs to do anti-aliasing anti-aliasing on neighboring pixels, increasing the graphics burden, which is usually caused by the recalculation and setting of some view frame.

Layers that are labeled yellow because the layers display the scaled pictures, and if they are downloaded over the network, they can be resolved by program updates to the determined drawing size. There are also systems navigation bar and tool bar background images are used with stretched (streched) pictures, which are also represented as yellow, which is normal, usually without modification. This problem generally has little impact on performance, but may be falsified at the edge.

(4) Color offscreen-rendered Yellow

Offscreen-rendering off-screen rendering means that when iOS wants to display a view, it needs to compute the view's bitmap in the background with the CPU, and then give the GPU a onscreen-rendering display on the screen, because displaying a view requires two calculations. So this offscreen-rendering will cause the app's graphics performance to degrade.

Most offscreen-rendering are related to the shadow and mask of the view layer, and the following conditions result in the offscreen-rendering:1 of the view. Use the core Graphics (classes that begin with CG). 2. Use the DrawRect () method, even if it is empty. 3. Set the Calayer property shouldrasterize to Yes. 4. The Calayer setmaskstobounds (masks) and setshadow* (shadow) methods are used. 5. Display text directly on the screen, including core text. 6. Set the uiviewgroupopacity.

This blog post designing for Ios:graphics & Performance A great introduction to Offsreen and graphics performance, (5) Color Copied Images Copied The image option labels the picture that was copied by the core animation when the app was drawn, and is labeled blue-green. Although I ran into it, my personal feelings had little impact on graphics performance. (6) Color Immediately,flash Updated regions, color OpenGL Fast Path Blue Color Immediately option indicates instruments when doing color-flush operation Cancels the 10 millisecond delay. The Flash Updated regions option is used to indicate in red the layers that are drawn on the screen using GPU calculations. The Color OpenGL Fast Path blue option is used to mark the content that is drawn on the screen by OpenGL compositor in blue. These three options are less useful for the analysis of graphics performance, and are usually used as a reference only.

File and network I/O

If you need to analyze the file and network I/O for your app, you can use the three instruments tools system Usage, file activity, and networks.

Tool system usage allows you to count the file and network IO Operational data that is applied in the running state. For example, we found another spike after the app started, which may be problematic, and we can use the details bar of the system usage tool to see if the application is causing a spike in read and write operations on which files.

The tool file activity can only be run in the emulator, so data collection may not be very accurate. It also gives detailed information about the file attributes, size, loading time, etc. that are read, and is suitable for use with system usage.

Network Tools can collect the application of TCP/IP and UDP usage information (the amount of data transmitted, all current TCP connections, etc.), not much, use the same line when analyzing the usage of networks.

Read more

There is a lot of knowledge about iOS app performance, which is just the tip of the iceberg, with a focus on recommending WWDC's session.

WWDC 2012:

  • 406:adopting Automatic Reference Counting
  • 238:ios App performance:graphics and animations
  • 242:ios App Performance:memory
  • 235:ios App performance:responsiveness
  • 409:learning Instruments
  • 706:networking Best Practices
  • 514:opengl ES Tools and techniques
  • 506:optimizing 2D Graphics and Animation performance
  • 601:optimizing Web Content in Uiwebviews and Websites on IOS
  • 225:up and running:making a great impression with every Launch

WWDC 2011:

    • 105:polishing Your app:tips and tricks to improve the responsiveness and performance
    • 121:understanding UIKit Rendering
    • 131 Performance optimization on iphone OS
    • 308:blocks and Grand Central Dispatch in practice
    • 323:introducing Automatic Reference Counting
    • 312:ios Performance and Power optimization with Instruments

There are several good blogs:

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/

IOS App Performance Optimization

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.