iOS Performance optimizations

Source: Internet
Author: User

The main reasons for performance problems are the same and different, but in the final analysis, it is all about memory usage, code efficiency, appropriate policy logic, code quality, installation package volume, and so on.

But from the perspective of user experience, when we have to put ourselves as users to play an application, then what will be concerned about it? If you are playing a hand tour, first of all, you do not want to play a sudden flash back, and then do not want to lag, followed by power consumption and consumption is not too serious, and finally the installation package hope to be smaller. The simple classification is as follows:

Fast: Avoid stuttering when using, fast response, reduce user wait time, meet user expectations.

Steady: Do not crash and not respond during user use.

Province: Save the flow and power consumption, reduce user costs, avoid the use of the phone caused by hot.

Small: A small installation package can reduce the user's installation costs.

One, fast

Application startup is slow, often lag in use, is very impact on the user experience, should try to avoid appearing. There are a lot of scenes, according to the scene can be divided into 4 categories: UI drawing, Application launch, page jump, event response. Cause a lot of reasons for the lag, but no matter how the reason and the scene, the end is through the device screen display to reach the user, in the final analysis is to display a problem,

According to the iOS system display principle, you can see that the root cause of the impact of painting has the following two aspects:

1. The drawing task is too heavy to draw a frame content too long.

2. The main thread is too busy, according to the system passed the VSYNC signal came when the data is not ready to cause dropped frames.

Drawing takes too long and there are tools that can help us locate the problem. The main thread is too busy to be aware that the main thread key responsibility is to handle user interaction, draw pixels on the screen, and load display related data, so there is a need to avoid any main thread of things, so that the application can maintain an immediate response to user action. Summing up, the main thread to do the following aspects of work:

1.UI Life Cycle Control

2. System Event Handling

3. Message Processing

4. Interface layout

5. Interface Drawing

6. Interface Refresh

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

Second, stable

The stability of the application is broadly defined, and there are many reasons for the stability, such as unreasonable memory usage, poorly considered code anomalies, unreasonable code logic, and so on, which will affect the stability of the application. The most common of the two scenarios are: Crash and ANR, these two errors will make the program unusable, the more common solution is as follows:

1. Improve code quality. For example, the code review during development, look at some code design logic, business rationality and so on.

2. Code static Scan Tool. Common tools include Clang Static Analyzer, Oclint, infer, and more.

3.Crash monitoring. The breakdown of information, abnormal information in a timely manner to record, so that the subsequent analysis to solve.

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

Third, the province

In mobile devices, the importance of batteries is self-evident, without electricity, nothing can be done. For operating system and device developers, power consumption optimization does not stop, to pursue longer standby time, and for an application, it is not possible to ignore the use of electricity, especially those classified as "battery killer" application, the end result is uninstalled. As a result, application developers need to minimize power consumption while implementing requirements.

1.CPU

The CPU is the primary hardware used by the app, regardless of whether the user is directly using it, and the app consumes CPU resources while working in the background and handling push notifications

The more you apply the calculation, the more power you consume. The older generation of devices consumes more power when the same basic operation is done, and the amount of computing consumed depends on different factors.

(There is a word called three people will have my teacher, in fact, as a developer, there is a learning atmosphere with a communication circle is particularly important this is a My iOS communication group 659170228, whether you are small white or Daniel Welcome to enter, are looking for a job can also join, we exchange learning, the words rough not rough, Learn from each other, make progress together and refuel together. )

2. Network

Intelligent Network access Management allows applications to respond faster and helps extend battery life. When you cannot access the network, you should defer subsequent network requests until the network connection is restored. In addition, you should avoid high bandwidth consumption without connecting to WiFi. For example, video streaming, as we all know, cellular wireless system (LTE,4G,3G, etc.) on the consumption of electricity is much larger than the WiFi signal, the source is the LTE device based on multi-input, multi-output technology, Using multiple concurrent signals to maintain LTE links on both ends, similarly, all cellular data links are periodically scanned for stronger signals. Therefore: we need

1) Check that the appropriate network connection is available before you perform any network operation

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

3). Location Manager and GPS

We all know that location services are very power-hungry, and using GPS to calculate coordinates requires two points of information:

1) time lock each GPS satellite broadcasts the only 1023-bit random number per millisecond, thus the data propagation rate is 1.024MBIT/S GPS receiver chip must be correctly aligned with the satellite's time slot

2) Frequency Lock the GPS receiver must calculate the signal error caused by the Doppler offset due to the relative motion of the receiver and the satellite

Computing coordinates will continue to use the CPU and GPS hardware resources, so they will quickly consume battery power, then how to reduce it?

1) Turn off the irrelevant features

Determine when to track changes in location, call the Startupdatinglocation method when tracing is required, and call the Stopupdatinglocation method without tracing.

You should also turn off location tracking when your app is running in the background or when users aren't chatting with someone else, and you should close location tracking when you browse the Media library, view your friends list, or adjust your app settings.

2) Use the network only when necessary

In order to improve the efficiency of power usage, iOS always keeps the wireless network off as much as possible. When an app needs to establish a network connection, iOS takes advantage of this opportunity to share a network session with a background app so that some low-priority can be processed, such as push notifications, email, etc.

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

To mitigate the hazards of this problem, your software needs to have a reserved network of users. You should periodically focus on using the network briefly instead of persisting the active data stream. Only then will the network hardware have a chance to shut down

4. Screen

The screen is very power-hungry, and the larger the screen, the more electricity it consumes. Of course, if your app is running in the foreground and interacting with the user, it's bound to use the screen and consume electricity.

Here are some scenarios to optimize the use of your screen:

1) Animation optimization

When the app is in the foreground, animation is used, and the animation is paused as soon as the app enters the background. Usually, you can listen Uiapplicationwillresignactivenotification or Uiapplicationdidenterbackgroundnotification notification events to pause or stop the animation, You can also resume the animation by listening for uiapplicationdidbecomeactivenotification notification events

2) Video optimization

During video playback, it's a good idea to keep the screen constant. You can use the Idletimerdisabled property of the UIApplication object to do this. Once YES is set, he will prevent the screen from sleeping, thus enabling a constant light.

Similar to animations, you can release and acquire locks with notifications from the appropriate app

Users always carry a mobile phone, so writing power-saving code is particularly important, after all, mobile phones are not ubiquitous, in the inability to reduce the complexity of the task, to provide a battery-sensitive solution and prompt users at the appropriate time, will make the user experience good.

Four, small

The app installation package size has no effect on app usage, but the larger the app's installation package, the higher the user download threshold, especially in the case of mobile networks, when users download the app, the size of the installation package is higher, so reducing the size of the installation package will allow more users to download and experience the product.

Of course, weight loss and reduced burden are good, but need to pay attention to the impact of slimming on the maintainability of the project, it is recommended to choose according to their own project skills.

The app installation package is made up of resources and executables, and the installation package is optimized from the following three sections.

Resource optimization:

    1. Delete useless resources

2. Delete duplicate resources

3. Lossless compression picture

4. Non-trivial resources for download

? Compilation optimizations:

1. Remove the debug symbol

2. Turn on compile optimization

3. Avoid compiling multiple schemas

? executable file Optimization:

1. Removing useless code

2. Statistical library occupancy, removal of useless libraries

3. Confusing class/method names

4. Reduce redundant strings

5.ARC->MRC (usually not recommended in special cases, will increase maintenance costs)

Reducing the size of iOS installation package is a lot of large and medium-sized apps to do, usually start with the resource files, Compress Pictures/audio, remove unnecessary resources. After the optimization of these resources, we can also try to thin the executable file, the larger the project, the larger the size of the executable file, and because the AppStore will encrypt the executable file, resulting in low compression of the executable file, compressed executable file for the entire app installation package volume ratio of about 80%~ 90%, it's still worth the optimization.

The following are some common optimization scenarios:

Tableviewcell multiplexing

In Cellforrowatindexpath: The callback only creates the instance, quickly returns to the cell, does not bind the data. Bind data (Assignment) when Willdisplaycell:forrowatindexpath:.

Height cache

When the TableView is sliding, Heightforrowatindexpath is constantly called: when the cell height needs to be adaptive, each callback calculates the height, which causes the UI to get stuck. To avoid repeating meaningless computations, cache height is required.

How to Cache?

Dictionary, Nscache.

Uitableview-fdtemplatelayoutcell

[If!supportlinebreaknewline]

[EndIf]

View-Level optimization

Do not create views dynamically

The cache is subview on the premise that the memory is controllable.

Use hidden.

[If!supportlinebreaknewline]

[EndIf]

Reduce the view level

Reduce the number of subviews and draw elements with a layer.

Use less clearcolor,masktobounds, shadow effects and more.

[If!supportlinebreaknewline]

[EndIf]

Reduce unnecessary drawing operations

Image

Do not use JPEG images, PNG images should be used.

Child thread Pre-decode (Decode), the main thread directly renders. Because when the image does not have a decode, assigning a value directly to ImageView will perform a decode operation.

Optimize the image size and try not to scale dynamically (Contentmode).

Make as many pictures as you can to display them.

[If!supportlinebreaknewline]

[EndIf]

Reduce transparent View

Using transparent view can cause blending, in the graphics processing of iOS, blending mainly refers to the calculation of mixed pixel colors. The most intuitive example is that we overlay two layers together, and if the first layer is transparent, then the color calculation of the final pixel needs to take the second layer into account as well. This process is 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 if the image contains a transparent channel, it will still cause blending).

[If!supportlinebreaknewline]

[EndIf]

Why does blending cause a loss of performance?

The reason is very intuitive, if a layer is opaque, the system directly displays the color of the layer. If the layer is transparent, it will cause more calculations because another layer needs to be included in the color calculation after blending.

Opaque is set 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 the image needs to be rendered before drawing to the current screen before it is drawn to the current screen.

In OpenGL, GPU screen rendering is available in the following two ways:

On-Screen

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

Off-screen

Rendering is off-screen rendering, which refers to a new buffer that the GPU creates in addition to the current screen buffer for rendering operations.

[If!supportlinebreaknewline]

[EndIf]

Summary

Performance optimization is not an update of one or two releases, it is a continuous requirement, continuous integration of iterative feedback. In the actual project, at the beginning of the project, due to manpower and project completion time constraints, performance optimization priority is relatively low, and so on into the project into the use phase, you need to improve the priority, but in the early stages of the project, in the design of the schema, performance optimization points need to be considered earlier, This reflects the technical skills of a programmer.

When it comes to the need for performance optimization, it often starts with the discovery of problems, then analyzes the cause and background of the problem, and then finds the best solution to solve the problem, which is the usual way of handling the work.

Reference articles

Draw pixels to the screen

iOS graphics principle and off-screen rendering, in 1.4.1, which is why Calayer has a property called opaque. If this property is No,gpu will not do any compositing, but simply copy from this layer, do not need to consider anything underneath it (because it is obscured by it). The opaque attribute in the NO,GPU will not do any compositing, and this sentence is wrong and should be for YES,GPU to do no compositing.

IOS tips for maintaining smooth interface

Advanced Graphics and animations for IOS Apps (session 419)

Using ASDK performance Tuning-improve the rendering performance of the IOS interface

Designing for Ios:graphics &

Performance

Optimized analysis of iOS off-screen rendering

Overview of iOS View rendering and performance tuning

IOS Off-screen rendering

Deep understanding of mobile-optimized off-screen rendering

IOS Fluency Performance optimization, CPU, GPU, off-screen rendering

IOS Graphics performance Optimization brocade set

Off-Screen Rendering Optimization: Example demonstration + Performance test

[If!supportlinebreaknewline]

[EndIf]
(There is a word called three people will have my teacher, in fact, as a developer, there is a learning atmosphere with a communication circle is particularly important this is a My iOS communication group 681503716, please note number worship, Daniel Welcome to enter, are looking for a job can also join, we exchange learning, the words rough not rough, Learn from each other, make progress together and refuel together. )

iOS Performance optimizations

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.