IOS App performance optimization and iosapp Performance Optimization

Source: Internet
Author: User

IOS App performance optimization and iosapp Performance Optimization
IOS App performance considerations

Although the performance of the iPhone is getting better and better, the functions of the app are getting more and more complex. performance has always been one of the core concerns of mobile development. We can say that an app has good performance. It doesn't mean that the app is running fast, but that the app starts fast, the UI feedback is timely, the list scrolling operation is smooth, and the memory usage is reasonable, of course, we cannot just Crash it. When developing applications, engineers should not only avoid performance pitfalls, but also quickly locate the cause when encountering pitfalls. Of course, you cannot guess the cause of performance problems. A reasonable method is to use tools to measure and evaluate the highest ROI problem and then optimize it.

This article describes how to analyze and optimize iOS app performance from the following points: startup time, user response, memory, graphic animation, file and network I/O. The performance analysis tool "Instruments" produced by Apple is used ".

Start Time

The duration of application startup is crucial to the first user experience. At the same time, the system also has strict requirements on the running time of application startup, recovery, and other States, when the application times out, the system will directly close the application. In the following common scenarios, the system requires the app runtime: * Launch 20 secondsResume 10 secondsSuspend 10 secondsQuit 6 secondsBackground Task 10 minutes

To obtain the exact time required for app startup, add the following code in main. c in the simplest way:

123
CFAbsoluteTime StartTime;int main(int argc, char **argv) {  StartTime = CFAbsoluteTimeGetCurrent();

Then the callback method in AppDelegateapplication:didFinishLaunchingWithOptionsAdd:

Dispatch_async (dispatch_get_main_queue (), ^ {NSLog (@ "Lauched in % f seconds. ", (CFAbsoluteTimeGetCurrent ()-StartTime) ;}); you may wonder why you can get the system startup time, because the Jobs submitted in dispatch_async will run in the next run lopp after the main app thread starts, the app has completed loading and will display the first frame of the screen, that is, the system will run before '-[UIApplication _ reportAppLaunchFinished. Is the use of Instruments tool Time Profiler run call stack, Instruments use method is recommended to see WWDC performance-related [session video] (https://developer.apple.com/videos/wwdc), text written too thin is not intuitive enough.

We can see in the system call[UIApplication _reportAppLaunchFinished]Previously completed system callbackapplication:didFinishLaunchingWithOptions.

The App startup includes the following parts (from WWDC 2012 Session 235 ):

1) Link and load: The dyld loading function can be displayed in the Time Profile. The Library is mapped to the address space and the binding and static initialization are completed at the same Time.

2) UIKit initialization: if the application's Root View Controller is implemented by XIB, it will also be initialized at startup.

3) Application callback: Call the callback of UIApplicationDeleagte:application:didFinishLaunchingWithOptions

4) first Core Animation call: method after startup-[UIApplication _resportAppLaunchFinished]CallingCA::Transaction::commitDraw the first frame. If your program starts slowly, you can first put operations unrelated to the display of the first screen and then execute them. If you load the first screen with the XIB file, the View layer in the XIB file should also be flat and should not have too many layers.

User response

How can users feel that your app responds quickly? Of course, the Operation triggered by the app User can get immediate response, that is, the User Event can be processed in a timely manner by the run loop of the main thread. What is run loop? It can be imagined as a select multiplexing for event processing. The run loop in the main thread is mainly used to process user-generated events, such as clicks and scrolling. In the future, we will discuss in detail the confusing run loop.

To make the run loop of the main thread better respond to user events, engineers should try to reduce the time required for the master thread to repeat, especially reading files, network operations, and a large number of operations, if it is a blocking operation, it is even more taboo. We can use multiple threads (NSThread, NSOperationQueue, GCD, And the next Blog will talk about the multiple threads) to remove the re-activity from the main thread, which is an explicit concurrency. There is also an implicit concurrency, such as view and layer animations, layer rendering, and PNG image decoding are all executed in another child thread. In addition to using multithreading technology to reduce the burden on the main thread, reducing the congestion in the main thread is also a way to improve user experience. The "Recod thread waiting" option in the Time Profiler tool in Instruments can be used to calculate the blocking system calls in each thread during app running, such as file read/write, network read/write send/recv, lock psynch_mutex_wait. The System Trace tool in Instruments records all underlying System calls.

Memory

Memory problems have always been an old and difficult problem for iOS apps. If they are not good, the program will burst. Because the iOS system does not have a Swap file (do you know why? Leave it to suspense) when the memory is insufficient, read-only data (such as code page) will be removed from the memory, and read from the disk as memory when necessary; data that can be read and written is not removed from the memory. However, if the occupied memory reaches a threshold value, the system will send a notification and callback so that the application release object can recycle the memory, if you still cannot reduce the memory usage, the system will directly close the application. Especially after iOS 5.0, if your app receives memory warning, the head is also placed on the chopping board like other apps, and may be killed at any time, it does not mean that the app will be killed in the background first.

In addition to the memory allocated on the heap (+[NSobject alloc]/malloc), There will be more places to use memory, such as code and global data (TEXT andDATA), thread stack, images, view layer backing store, and so on. Therefore, to solve the memory issue is not just as simple as applying for less memory when developing apps.

With the amazing ARC, the memory problems are relatively less, and the development efficiency is also improved. However, many companies still use manual memory management for their projects due to historical reasons. Static analysis function provided by Xcode can help you discover some problems in advance. However, some memory problems cannot be found through static analysis. For example, we are constantly using the memory and cannot release it in time, the static analyzer cannot be used for analysis. In this case, you can use the Allocations and Leaks tools of Instruments to check the memory usage and leakage during runtime.

The Allocations tool can intuitively reflect the memory usage of the app. It also likes the "Mark Heap" function in Heapshot Analysis in the lower half of the left. For example, you can click "Mark Heap" before entering a page, and then return to the previous page and click "Mark Heap ", if the memory you applied for on the page is properly released, the heap memory growth should be reduced to 0 (see the lower-right part ).

Another serious memory usage problem is that the released memory is referenced, which directly causes the application to crash, allocation has an Enable NSZombie detection option that can be marked when the application uses the released memory and displays the call stack information of the error. This provides the most direct help to solve the problem. Of course, the disadvantage is that the EXEC_BAD_ACCESS error must be reproduced.

The tool Leaks can directly mark the Code with Memory leakage when the application is running. If memory leakage occurs, you can view the leaked objects and method call stacks from the leaked details, most problems are still well solved.

Graphics and Animation

The graphic performance has a direct impact on the user experience. The Core Animation tool in Instruments is used to measure the graphic performance on the physical machine. The graphic performance of the application is determined by the refresh frequency of the view. For example, when a complex list is rolled, the update rate should be close to 60 FPS to make the user feel fluent. From this number, we can also calculate that the maximum response time of the run loop should be 16 milliseconds.

After starting the Core Animation tool of Instruments, you can find that there are a bunch of options in the lower left. Let's introduce them one by one:

1) Color Blended Layers

Instruments can display the Blended Layer (marked in red) on the physical machine. The Blended Layer is Transparent ), when rendering these views, the system needs to mix the view and the lower view to calculate the actual color of the pixel. If there are many blended layers, then, when rolling the list, you want to have a smooth effect.

It is also easy to solve the blended layer problem. Check the opaque attribute of the view in the red area. Remember to set it to YES and check whether the backgroundColor attribute is correct.[UIColor clearColor]You need to know that the background color is clear color, which is an enemy of the graphic performance. It basically means that the blended layer cannot run. Why? Think for yourself :)

2) Color Hits Green and Misses Red

Many view layers are highly rendered due to Shadow, Mask, Gradient, and other reasons. Therefore, UIKit provides APIs for caching these layers: [Layer setShouldRasterize: YES], the system caches these layers into Bitmap bitmaps for rendering. If the Layer fails, the Bitmap is discarded and regenerated. The advantage of layer Rasterization is that it has little impact on the refreshing rate. The disadvantage is that the Bitmap cache after the deletion processing requires memory usage, and when the layer needs to be scaled, perform additional calculations on the Bitmap after deletion. When this option is used, if the Rasterized Layer is invalid, it is marked in red. If it is marked in green. When the test application frequently flashes the red annotation layer, it indicates that the Rasterization of the layer is not very effective.

3) Color Misaligned Images

Misaligned Image indicates that the points to be drawn cannot be directly mapped to the pixels on the Frequency Screen. In this case, the system needs to perform anti-aliasing on adjacent pixels, increasing the Image burden, this problem usually occurs when the Frame of some views is re-computed and set.

Marked as yellow, because the layer displays scaled images. If these images are downloaded online, you can solve this problem by updating the program to a determined drawing size. In addition, some background images of Navigation Bar and Tool Bar use Streched images, which are also yellow. This is a normal situation and usually does not need to be modified. This problem generally has little impact on performance, but may be virtualized 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 calculate the Bitmap of the view with CPU in the background, and then give it to the GPU for Onscreen-Rendering to display on the screen, because it takes two computations to display a view, this Offscreen-Rendering will cause the image performance of the app to decline.

Most Offscreen-Rendering operations are related to the Shadow and Mask of the view Layer. In the following cases, Offscreen-Rendering of the view is performed: 1. Use Core Graphics (class starting with CG ). 2. Use the drawRect () method, even if it is null. 3. Set the attribute shouldRasterize of CALayer to YES. 4. The setMasksToBounds (masks) and setShadow * (shadow) Methods of CALayer are used. 5. display Text directly on the screen, including Core Text. 6. Set UIViewGroupOpacity.

This blog post, Designing for iOS: Graphics & Performance, provides a great introduction to offsreen and graphic Performance (5) the Color Copied Images Copied Image option can mark the Image Copied by Core Animation when the application is drawn, and the Image is marked as blue-green. Although I have encountered it during runtime, I personally feel that it has little impact on the image performance. (6) Color Immediately, Flash Updated Regions, Color OpenGL Fast Path Blue Color Immediately indicates that Instruments cancel the delay of 10 ms during the color-flush operation. The Flash Updated Regions option is used to indicate the layers that are drawn using GPU computing on the screen in red. The Color OpenGL Fast Path Blue option is used to mark the content drawn by OpenGL compositor on the screen in Blue. These three options have little significance for graph performance analysis and are generally used as a reference only.

File and network I/O

If you need to analyze the app File and Network I/O, you can use these three Instruments tools: System Usage, File Activity, and Network.

The Tool System Usage can collect statistics on application files and network I/O operation data in the running state. For example, if we find another peak value after the application is started, this may cause a problem. We can use the details bar of the System Usage tool to check which files the application is performing read/write operations on.

The File Activity tool can only be run in the simulator, so data collection may not be very accurate. It also provides detailed information about the properties, size, and loading time of the file to be read, and is suitable for use with System Usage.

The Network tool can collect the application's TCP/IP and UDP usage information (the amount of data transmitted, all current TCP connections, etc, it is okay to use network usage analysis.

Read more

There is a lot of knowledge about iOS App performance. The above is just the tip of the iceberg. We recommend the WWDC session.

2012 WWDC:

  • 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

2011 WWDC:

  • 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 also a few 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/


How to optimize the APP project in IOS development projects? Is the APP running faster? (At least three points)

1. Optimized Memory Management
2. Use delayed loading for large data volumes
3. How to cache data that requires multiple requests

In addition to 360,

Currently, IOS does not have any available cleanup software, and the 360 manage QQ manager cannot clean up garbage. You can only manually clear or brush the machine!

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.