Common performance optimization techniques in iOS development

Common performance optimization techniques in iOS development

What are the main causes of performance problems? The reasons are the same and different, but in the final analysis, it is nothing more than memory usage, code efficiency, appropriate strategy logic, code quality, and installation package size.

But from the perspective of user experience, when we are in a position to play an app as a user, what do we care about? If you are playing a mobile game, first of all you don't want to play and crash suddenly, then you don't want to freeze, secondly, you don't want to consume too much power and data, and finally, the installation package hopes to be smaller. The simple classification is as follows:

Fast: Avoid lags during use, fast response speed, reduce user waiting time, and meet user expectations. Stable: Don't crash and become unresponsive during user use. Saving: Save data and power consumption, reduce user costs, and avoid hot phone use. Small: The small installation package can reduce the user's installation cost.

1. fast

Applications are slow to start and often freeze during use, which greatly affects user experience and should be avoided as much as possible. There are many stagnant scenes, which can be divided into 4 categories according to scenes: UI drawing, application startup, page jump, and event response. There are many reasons for the lag, but no matter what the reason and the scene, the user is finally reached through the display on the device screen. In the final analysis, the display is defective.

According to the display principle of the iOS  system, it can be seen that the root causes affecting the drawing are as follows:

1. The drawing task is too heavy and it takes too long to draw a frame of content.

2. The main thread is too busy, and the data is not ready when the VSYNC signal sent by the system comes, causing frame loss.

It takes too long to draw, and there are some tools that can help us locate the problem. If the main thread is too busy, you need to pay attention. The key responsibility of the main thread is to handle user interactions, draw pixels on the screen, and load and display related data. Therefore, it is particularly necessary to avoid any main thread issues so that the application can maintain user operations. Immediate response. To sum up, the main thread mainly does the following work:

1. UI life cycle control

2. System event processing

3. Message processing

4. Interface layout

5. Interface drawing

6. Interface refresh

In addition, you should try to avoid putting other processing in the main thread, particularly complex data calculations and network requests.

2. stable

The stability of the application has a broad definition, and there are many reasons that affect the stability, such as unreasonable memory usage, incomplete consideration of code exception scenarios, and unreasonable code logic, which will all affect the stability of the application. The two most common scenarios are: Crash and ANR. These two errors will make the program unusable. The more common solutions are as follows:

1. Improve code quality. For example, code review during development, look at some code design logic, business rationality, etc.

2. Code static scanning tool. Common tools include Clang Static Analyzer, OCLint, Infer, etc.

3. Crash monitoring. Record some crash information and abnormal information in time for subsequent analysis and resolution.

4. Crash upload mechanism. After the crash, try to save the log locally, and then upload the log information when the network is normal next time.

3. province

In mobile devices, the importance of batteries is self-evident, and nothing can be done without electricity. For operating system and device developers, power consumption optimization has not stopped and pursued longer standby time. For an application, it is not possible to ignore the power usage problem, especially those classified as "battery killers "The final result is to be uninstalled. Therefore, application developers need to minimize power consumption while fulfilling their requirements.

1.CPU

Regardless of whether the user is directly using it, the CPU is the main hardware used by the application. When operating in the background and processing push notifications, the application will still consume CPU resources

The more the application calculates, the more power it consumes. When completing the same basic operation, the older generation of devices will consume more power, and the consumption of calculations depends on different factors.

2. Network

Intelligent network access management can make the application respond faster and help extend battery life. When you cannot access the network, you should postpone subsequent network requests until the network connection is restored. In addition, you should avoid the situation when the WiFi is not connected For example, video streaming. It is well known that cellular wireless systems (LTE, 4G, 3G, etc.) consume much more power than WiFi signals. The root cause is that LTE devices are based on multi-input and multi-output technologies and use multiple Concurrent signals are used to maintain the LTE link at both ends. Similarly, all cellular data links will be scanned regularly to find a stronger signal. Therefore: we need

1) Before performing any network operations, first check whether a suitable network connection is available

2) Continuously monitor the availability of the network and give appropriate feedback when the link status changes

3). Positioning manager and GPS

We all know that location services are very power-consuming. Using GPS to calculate coordinates requires two points of information:

1) Time lock Each GPS satellite broadcasts a unique 1023-bit random number every millisecond, so the data transmission rate is 1.024Mbit/s. The GPS receiving chip must be correctly aligned with the satellite's time lock slot

2) The frequency-locked GPS receiver must calculate the signal error caused by the Doppler shift caused by the relative motion of the receiver and the satellite

Calculating coordinates will continuously use CPU and GPS hardware resources, so they will quickly consume battery power, so how to reduce it?

1 ) Turn off irrelevant features

To determine when you need to track the change of location, call the startUpdatingLocation method when you need to track, and call the stopUpdatingLocation method when you don't need to track.

When the app is running in the background or the user is not chatting with others, you should also turn off location tracking. In other words, you should turn off location tracking when you browse the media library, view the friend list, or adjust the application settings.

2 ) Use the network only when necessary

In order to improve the efficiency of battery usage,  IOS  always keeps the wireless network off as much as possible. When the application needs to establish a network connection, IOS will use this opportunity to share the network session with the background application, so that some low priority can be processed, such as push notifications , Receive emails, etc.

The key is that every time a user establishes a network connection, the network hardware will maintain a few more seconds of active time after the connection is completed. Each centralized network communication consumes a lot of power.

To alleviate the harm caused by this problem, your software needs to use the network reserved. You should use the network regularly and briefly instead of continuously maintaining an active data stream. Only in this way can the network hardware have the opportunity to shut down

4. Screen

The screen consumes a lot of power, and the larger the screen, the more power it consumes. Of course, if your app is running in the foreground and interacting with the user, it will inevitably use the screen and consume power

Here are some options to optimize the use of the screen:

1) Animation optimization

When the app is in the foreground, use the animation. Once the app enters the background, the animation will be paused immediately. Generally speaking, you can pause or stop the animation by listening to the notification event of UIApplicationWillResignActiveNotification or UIApplicationDIdEnterBackgroundNotification, or you can resume it by listening to the notification event of UIApplicationDidBecomeActiveNotification Animation

2) Video optimization

During video playback, it is best to keep the screen constant. You can use the idleTimerDisabled property of the UIApplication object to achieve this purpose. Once YES is set, it will prevent the screen from sleeping and achieve constant light.

Similar to animation, you can release and acquire the lock through the notification of the corresponding app

Users always carry their mobile phones with them, so it is particularly important to write power-saving codes. After all, the mobile power of mobile phones is not everywhere. When the complexity of the task cannot be reduced, provide a solution that is sensitive to battery power and at the right time Prompt the user to make the user experience good.

4. small

The size of the application installation package has no effect on the use of the application, but the larger the installation package of the application, the higher the threshold for users to download. Especially in the case of mobile networks, users have higher requirements for the size of the installation package when downloading applications. Therefore, Reducing the size of the installation package can make more users willing to download and experience the product.

Of course, weight reduction and burden reduction are good, but you need to pay attention to the impact of weight loss on the maintainability of the project. It is recommended to select skills according to your own project.

The App installation package is composed of two parts: resources and executable files. The installation package is optimized from the following three parts.

Resource optimization:

1. Delete useless resources 2. Delete duplicate resources 3. Losslessly compress pictures 4. Change infrequent resources to download

Compilation optimization:

1. Remove the debug symbol 2. Turn on compilation optimization 3. Avoid compiling multiple architectures

Executable file optimization:

1. Remove useless code 2. Statistics library occupancy, remove useless library 3. Confusion class/method name 4. Reduce redundant strings 5. ARC->MRC (Generally, it is not recommended to do this under special circumstances, which will increase maintenance costs)

Reducing the size of the iOS installation package is something that many medium and large apps have to do. Generally, resource files are first started, pictures/audio are compressed, and unnecessary resources are removed. These resource optimization done, we can also try to slim down the executable file, the larger the project, the greater the volume occupied by the executable file, and because AppStore would executable file encryption , resulting in low compression executable file, The compressed executable file accounts for about 80%~90% of the volume of the entire APP installation package, which is still worth optimizing.

Here are some common optimization schemes:

TableViewCell reuse

In the cellForRowAtIndexPath: callback, only an instance is created, the cell is returned quickly, and no data is bound. Binding data (assignment) when willDisplayCell: forRowAtIndexPath:.

Highly cached

When the tableView slides, heightForRowAtIndexPath: will be called continuously. When the cell height needs to be adaptive, the height must be calculated every time the callback is made, which will cause the UI to freeze. In order to avoid duplication of meaningless calculations, the cache height is required.

How to cache?

 NSCache 

UITableView-FDTemplateLayoutCell

[if !supportLineBreakNewLine]

[endif]

 

 

 subview 

 hidden 

[if !supportLineBreakNewLine]

[endif]

 

 subviews layer 

 clearColor maskToBounds 

[if !supportLineBreakNewLine]

[endif]

 

 
 

Don't use JPEG images, but use PNG images.

The child thread pre-decodes (Decode), and the main thread renders directly. Because when the image has no Decode, directly assigning to the imageView will perform a Decode operation.

Optimize the image size, try not to zoom dynamically (contentMode).

Combine as many pictures as possible into one for display.

[if !supportLineBreakNewLine]

[endif]
 

Reduce transparent view

Using a transparent view will cause blending. In iOS graphics processing, blending mainly refers to the calculation of mixed pixel colors. The most intuitive example is that we superimpose two layers together. If the first layer is transparent, the final pixel color calculation needs to take the second layer into consideration. This process is known as Blending.

Causes of blending:

UIView's alpha<1.

The image of UIImageView contains an alpha channel (even if the alpha of UIImageView is 1, but as long as the image contains a transparent channel, it will still cause blending).

[if !supportLineBreakNewLine]

[endif]
 

Why does blending cause performance loss?

The reason is very intuitive. If a layer is opaque, the system can directly display the color of the layer. If the layer is transparent, it will cause more calculations, because another layer needs to be included to calculate the mixed color.

Set opaque to YES to reduce performance consumption, because the GPU will not do any compositing, but simply copy from this layer.

[if !supportLineBreakNewLine]

[endif]
 

Reduce off-screen rendering

Off-screen rendering means that before the image is drawn to the current screen, it needs to be rendered once before being drawn to the current screen.

In OpenGL, GPU screen rendering has the following two methods:

On-Screen

Rendering refers to the current screen rendering, which means that the GPU rendering operation is performed in the screen buffer currently used for display.

Off-Screen

Rendering is off-screen rendering, which refers to the GPU opening a new buffer outside the current screen buffer for rendering operations.

[if !supportLineBreakNewLine]

[endif]
 

summary

Performance optimization is not something that can be solved by updating one or two versions. It is a continuous demand and continuous integration of iterative feedback. In actual projects, at the beginning of the project, due to manpower and project completion time constraints, the priority of performance optimization is relatively low. When the project is put into use, the priority needs to be increased. However, at the beginning of the project, in the design When constructing the scheme, the points of performance optimization also need to be considered in advance, which reflects the technical skills of a programmer.

When there is a need for performance optimization, it usually starts from the discovery of the problem, and then analyzes the cause and background of the problem, and then finds the optimal solution, and finally solves the problem. This is also a common processing method used in daily work.