IOS performance optimization policy

Source: Internet
Author: User

I. Performance Optimization Strategies
Performance issue handling process

Discover/reproduce Problems
Analysis Using Tools
Assumptions
Improved code and Design
Repeat the preceding four steps until the problem is resolved.
Main Performance Optimization Strategies:

Do not do useless work: Do not spend several hundred ms on logging during startup, do not perform multiple queries for the same data
Try to reuse: for objects that are expensive to create, you must reuse them instead of recreate them.
Cell of Table View
Formatter of Date/Number
Regular Expression
SQLite statement
Faster design and programming: select the correct set object and Algorithm for programming, select the appropriate data storage format (plist, SQLite), and optimize SQLite query statements.
Optimize in advance
For expensive computing, calculation is required in advance. Duplicate events in iCal are calculated in advance and saved to the database.
Computing and caching objects in advance may occupy a large amount of memory. Do not declare these objects as static and resident memory.
Optimization afterwards: asynchronous loading and lazy loading
Optimization for Scalability: when there are 10, 100, 1000, or more data records, the performance of applications should not increase in an order of magnitude, otherwise, it cannot be used.
To put it bluntly, I rarely encounter performance problems. Many of the previously assumed performance problems do not exist at all. The pre-plan also prevents performance problems, so we should forget it for the time being. Of course, some common sense design to improve performance is still necessary.

Ii. iOS app startup Speed Optimization
Many app developers do not pay attention to the app startup speed, which is a disaster for users who use fragmented scenarios.

IOS app startup speed
When the application starts, a magnified animation is played. The iPhone is 400 ms, and the iPad is 500 ms. The ideal startup speed is that after the animation is played, you can use it.

If the application is too slow to start, the user will give up or even never return. Aside from the code, if you hold the thinking of PC-side games and stand-alone games, you can impose company logos and start animations when starting a game, and you cannot skip them. This will also greatly reduce your success rate.

IOS system "Watchdog"

To prevent an application from occupying too much system resources, Apple engineers who developed iOS designed a "Watchdog" mechanism. In different scenarios, the "Watchdog" monitors the performance of applications. If it exceeds the running time specified in this scenario, the "Watchdog" forces the process of the application to end. In the crashlog, developers will see error codes such as 0x8badf00d ("dog" Eats bad food and is very upset ).
Scene "Watchdog" timeout
Start 20 seconds
Resume running for 10 seconds
Process suspension: 10 seconds
6 seconds to exit the application
10 minutes in the background
It is worth noting that during debugging, Xcode will disable "Watchdog ".

How to test the start time:
Two Methods: NSLog and Time Profiler.

Use NSLog
1 CFAbsoluteTime StartTime;
2 int main (int argc, char ** argv ){
3 StartTime = CFAbsoluteTimeGetCurrent ();
4 //... 5} 6
7-(void) applicationDidFinishLaunching :( UIApplication *) app {
8 dispatch_async (dispatch_get_main_queue (), ^ {
9
NSLog (@ "Launched in % f sec", CFAbsoluteTimeGetCurrent ()-StartTime );
10
}); 11 //... 12}
Use Time Profiler
Instruments-> Time Profiler
Profile your app
Switch to CPU strategy view and find the first frame of your app startup.
Search-[UIApplication _ reportAppLaunchFinished]
Find the last frame that contains-[UIApplication _ reportAppLaunchFinished] to calculate the start time.
IOS App startup process

Link and load Framework and static lib
UIKit Initialization
Application callback
First Core Animation transaction
Note the following when linking and loading the Framework and static lib:

Each Framework increases the startup time and memory usage.
Do not link unnecessary frameworks
Required Framework. Do not set the box office to Optional.
Optional is used only when the Framework released after the Deployment Target is used (for example, if your Deployment Target is iOS 3.0 and you need to connect to StoreKit)
Avoid creating global C ++ objects
Note the following when initializing UIKit:

The font, status bar, user ults, and main nib will be initialized.
Keep main nib as small as possible
User ults is essentially a plist file, and the stored data is deserialized at the same time. Do not store images and other big data in user defaults.
Application callback:
Application: willfinishlaunchingwitexceptions:
Restore Application Status
Application: didfinishlaunchingwitexceptions:
I always think that the essence of design is a compromise. When you are excited to optimize the startup speed by MS and ignore the 10-second animation, you should think about what you should do. Doing the right thing is more important than doing the right thing.
Iii. Event Processing-saving the main thread
Users often comment that the app uses the word "choppy" because the main thread is occupied. User events are handled in the main thread, including click, scroll, accelerator, Proximity Sensor.
To ensure smooth event processing, the following optimization is required:

To minimize the CPU usage of the main thread and remove the work from the main thread, do not block the main thread

In the previous two articles, we have access to Time Profiler. It analyzes the CPU usage of different threads and provides the CPU usage percentage of the call stack. If the app is "choppy" and the result of Time Profiler can find a clear high-occupancy stack, You need to optimize it.

Remove work from main thread-implicit concurrency
In order to get a smoother interaction experience, iOS has already helped us with a lot of things, so Android is not so lucky. IOS removes the following tasks from the main thread:

View and layer Animations (the calculation before the animation is drawn, rather than the drawing process)
Combined Layer computing (stacking after drawing)
PNG decoding (yes, you are not mistaken; and the multi-core CPU is used)
Note that Scrolling is not an animation, but constantly receives and processes events in the Main Run Loop.

Remove work from main thread-explicit concurrency
Here is what developers need to do. Disk, network, and other I/O will block the thread, do not put them in the main thread. Common technologies include:
Grand Central Dispatch (GCD)
NSOperationQueue
NSThread
After iOS 4.0, the easy-to-use GCD technology is widely used. For example:
Dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 ),
^ {
// Do something in background dispatch_async (dispatch_get_main_queue (), ^ {
// Do something on main thread
});});
GCD traps
GCD is actually a thread, but it provides a high-level abstraction. Too many threads will inevitably cause performance loss. Therefore, GCD designs a maximum allowed thread value (transparent to developers, regardless of the number of threads ). How can this problem be solved?

Serializing queues
Use Dispatch sources
Use NSOperationQueue with restrictions
Use the asynchronous method provided by Cocoa Touch
Another trap is thread security:

UIKit must be used in the main thread, except UIGraphics, UIBezierPath, and UIImage
Most CG, CA, and Foundation classes are not thread-safe.
If you use ojbc runtime for introspection, because it is thread safe, it may lead to competition.
In addition, DISPATCH_QUEUE_PRIORITY_BACKGROUND is added to iOS 4.3, which has a very low priority. This priority is only used for real background tasks that do not care much about the completion time. To indicate a lower priority, you usually need DISPATCH_QUEUE_PRIORITY_LOW.
Do not block the main thread
Even if it takes a small amount of CPU Time (if you see the data in Time Profiler), it may block the main thread. Disks, networks, locks, dispatch_sync, and messages sent to other processes/threads will block the main thread. Time Profiler can only detect stacks that occupy too much CPU, but cannot detect these IO problems.

Most blocking events are accompanied by a system call, such:
Read/write-read/write files
Send/recv-send and receive Network Data
Psynch_mutex_wait-obtain the lock
Mach_msg-IPC
The Instrumentor of System Trace records all System calls and the waiting time of each call. If you find that the CPU Time is very low but the Wait Time is very high in System Trace, it means that processing I/O in the main thread has seriously damaged app performance.

It ensures low CPU usage of the main thread and moves I/O to other threads, which can greatly improve the processing capability of the main thread to interactive events. I suggest that developers do not have to assume that the problem exists unless they have encountered problems before when writing code. 80% of optimization is unnecessary.

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.