[In-depth introduction to cocoa] IOS Program Performance Optimization

Source: Internet
Author: User
[Cocoa] IOS Program Performance Optimization Luo chaohui (http: // http://www.cnblogs.com/kesalin) CC license, reproduced please indicate the source of IOS application is very focused on user experience, not only requires the interface design reasonable and beautiful, it also requires a variety of UIS to be responsive. I believe everyone has no good impression on the tableview application that is just a drag-and-drop clip. 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. Computing 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...DoubleDeltatime =[[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 <Mach/mach_time.h> //  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 complex views,Use drawrect instead of loading it from nib.

 

5. For tableview,Reuse cells; reduce cell initialization workload and delayed loading; Use drawrect for Custom Complex cells; cache as many items as possible, including cell height; minimize cell opacity; 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, suchCalendar 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) GuaranteeBackgroundCode ExecutionNormal. 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 a large number of cycles, use Methodforselector Obtain the method imp, and then directly use the IMP in the loop body. 13. About memory release in Release memory in didreceivememorywarning, such as cache images and views. Remember to call [supper didreceivemorywarning]. ClearFunctionDidreceivememorywarning, viewdidunload, and dealloc are both at the end of the method.Call the supper 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 as much as possible, such as table cell, Date/number formatters, regular expression, SQLite statement, etc. 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.