13 tips for iOS Performance Optimization

Source: Internet
Author: User

The iOS app pays great attention to user experience. It not only requires a reasonable and beautiful UI design, but also requires a variety of UIS to be responsive. I believe everyone has no good impression on the TableView app with a drag-and-drop effect. Do you still remember the speed of 12306? I believe everyone can't stand it. In order to improve the running speed of iOS, I will introduce some methods I have used to improve the running efficiency of iOS programs and share them with you, hoping to receive more feedback and suggestions.

1. Calculate the code running time: trust data, and do not trust it. But pay attention to the differences between the simulator and the real machine.

The simplest tool is NSDate, but the precision is not very good.

NSDate * tmpStartData = [[NSDate date] retain];

// You code here...

Double deltaTime = [[NSDate date] timeIntervalSinceDate: tmpStartData];

NSLog (@ ">>>>>>>>>> cost time = % f", deltaTime );

Or place the Running code in the block parameter of the following method, and then return the running time:


# Import // For mach_absolute_time () and friends

CGFloat BNRTimeBlock (void (^ block) (void )){

Mach_timebase_info_data_t info;

If (mach_timebase_info (& info )! = KERN_SUCCESS) return-1.0;

Uint64_t start = mach_absolute_time ();

Block ();

Uint64_t end = mach_absolute_time ();

Uint64_t elapsed = end-start;

Uint64_t nanos = elapsed * info. numer/info. denom;

Return (CGFloat) nanos/NSEC_PER_SEC;

}


2. Make good use of performance analysis tools.

XCode comes with many powerful analysis tools, including static Analyze tools and runtime Profile tools.


3. About Images

Priority[UIImage imageNamed: @ ""];

[UIImage imageNamed:] is more efficient than [[UIImage alloc] initWithContentsOfFile:] and [UIImage alloc [initWithData, this is because iOS will bring images loaded with cache via [UIImage imageNamed:]. However, this method has a disadvantage that it can only load images in application bundle, images downloaded over the Internet are powerless. I am used to customizing an ImageCache class to cache images by myself.

Do not use full-screen background images; Use gradient images to replace hard-coded gradient images; Use gradient images as narrow as possible, and then apply them to actual scenarios.

4. For views with complex structures, use drawRect instead of loading them from nib.

5. For TableView, reuse cell; reduce the workload of cell initialization and delay loading; Use drawRect for self-painting when customizing complex cells; as many items as possible in Cache, including cell height; make cell opacity as much as possible; avoid using image features, such as gradients.

6. Use autoreleasepool in the thread.

7. Run some less important tasks in idle.


-(Void) idleNotificationMethod {

// Do something here

}


-(Void) registerForIdleNotification

{

[[Nsicationcenter center defacenter center] addObserver: self

Selector: @ selector (idleNotificationMethod)

Name: @ "IdleNotification"

Object: nil];

NSNotification * notification = [NSNotification

NotificationWithName: @ "IdleNotification" object: nil];

[[NSNotificationQueue defaultQueue] enqueueNotification: notification

PostingStyle: NSPostWhenIdle];

}


8. Do not perform time-consuming operations in viewWillAppear.

ViewWillAppear: it is called before the view display. for efficiency reasons, do not handle complicated and time-consuming tasks in this method. You should set simple things such as the view display attribute in this method, such as the background color and font. Otherwise, the user will obviously feel that the view is slow.

9. Use multiple threads to delay loading resources. For example, for network image display in common TableViewCell, use a default image first, and then enable the thread to download the network image. After the image is downloaded, replace the default image.

10. Background tasks

After the system enters the background, it generally takes only 10 minutes to run. Therefore, there are many precautions:

  • A) Minimize memory usage. When the memory is insufficient, iOS will kill the apps that consume the most memory.
  • B) release all shared resources, such as Calendar and Address book. When the application enters the background, if it is still in use or has not released shared resources, iOS will kill the application immediately.
  • C) correctly handle App lifecycle events. When you enter the background, you should keep the application data so that it can be restored when you return to the foreground. When you enter the inactive status, you should suspend the current business flow. IOS apps run in the background for a limited amount of time, so the background code should not execute very time-consuming tasks. If possible, multithreading is used. When entering the background, iOS will save a snapshot of the current App, so that it will be displayed to users when appropriate (when loading views and data) to improve user experience, therefore, when entering the background, you should avoid presenting user information on the screen, so as not to disclose your personal data.
  • D) Do not update the UI or execute code that consumes a lot of CPU or batteries. After entering the background, you should not execute unnecessary tasks, do not execute OpenGL ES calls, cancel Bonjour services, correctly handle network connection failures, and avoid updating the UI, clear all warnings or other pop-up dialog boxes.
  • E) Ensure that the background code is executed normally and handle exceptions.
  • F) correctly responds to system changes in the background. For example, if the device rotates the message "UIDeviceOrientationDidChangeNotification sigsignificanttimechangenoication ication", the user sets NSUserDefaultsDidChangeNotification by default, and the localization language changes NSCurrentLocaleDidChangeNotification.

    11. If the key code uses C/C ++/asm for higher efficiency, use C/C ++/asm.

    12. If a method is used in a loop with many cycles, use methodForSelector to obtain the method IMP before entering the loop, and then directly use the IMP in the loop body.

    13. About memory release

    Release the memory in didReceiveMemoryWarning, such as the cache image and view, and remember to call [supper didReceiveMemoryWarning]. The cleanup functions didReceiveMemoryWarning, viewDidUnload, and dealloc call the supper method at the end of the method.

    14. Improved APP loading speed

    Avoid using static initialization, including static c ++ objects. The code that will run during loading, such as + (void) load {}, will cause extra code to run before the Main function.

    16. Change the cache space time. Cache is a common type of space-to-time delivery of performance. It can be used in many occasions.

    Cache reusable objects, such as table cell, date/number formatters, regular expressions, and sqlite statements.

    17. About Databases

    The sqlite statements that are frequently used in the cache; the database query statements are optimized, and sqlite3_trace and sqlite3_profile are used to find statements with poor performance; if possible, the cache query results are slow. When sqlite_prepare is used, SQL queries are compiled into bytecode. bind is used to reuse prepared statements.

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.