iOS App performance - Things to take care

download iOS App performance - Things to take care

of 25

  • date post

  • Category


  • view

  • download


Embed Size (px)


iOS App performance - Things to take care

Transcript of iOS App performance - Things to take care

  • 1. iOS App PerformanceThings to Take CareGurpreet Singh SachdevaEngineering Manager @ Yahoo

2. Who should attend this session? If you are developing or planning to developiOS apps and looking for tips to make yourapps fast then you are right place. Pre-requisite: Basic Objective-C knowledge 3. Why performance is important? Faster apps provide a better user experience Users expect high performance If your app is slow or unresponsive it is boundto get bad reviews and loose user base. Remember, mobile devices have less RAM. 4. Performance Tips Use ARC In addition to helping you avoid memory leaks, ARC canalso improve your performance, by making sure thatobjects are de-allocated as soon as they are no longerneeded. These days, you should always use ARC in your projects! 5. Performance Tips Dont block the main thread You should never do any heavy lifting on the mainthread. Remember, UIKit does all of its work on themain thread, such as drawing, managing touches, andresponding to input. Most cases of blocking the main thread occur when yourapp is performing an I/O operation which involves anytask that needs to read or write from an externalsource, such as the disk or the network. You can perform network tasks asynchronously by usingthis method on NSURLConnection 6. Performance Tips Use a reuseIdentifier where appropriate A table views data source should generally reuseUITableViewCell objects when it assigns cells to rows. Otherwise, table view will configure new cell each timea row is displayed. This is an expensive operation andwill affect the scrolling performance of your app To use reuseIdentifiers, call this method from your datasource object when asked to provide a new cell for thetable view:static NSString *CellIdentifier = @"Cell";UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; 7. Performance Tips Avoid fat XIBs If you are still using XIB files for some reason (may be forsupporting pre iOS 5 devices) then make them asuncomplicated as possible. Note that when you load a XIB into memory, all of itscontents are loaded into memory, including any images. If you have a view youre not using immediately, then yourewasting precious memory. Its worth noting that this wont happen with storyboards,since a storyboard will only instantiate a view controller whenits needed. 8. Performance Tips Size images to Image Views Scaling images on the fly can be expensive, especially ifyour UIImageView is embedded in a UIScrollView. If the image is downloaded from a remote service,sometimes you dont have control over the size, or youmight not be able to scale it on the server prior todownloading. 9. Performance Tips Choose the correct Collection Learning to use the most appropriate class or object forthe task at hand is fundamental to writing efficientcode. This is especially true when dealing withcollections. There is a document on Apples Developer Library thatexplains in detail the differences between the availableclasses, as well as which situations suit each class. Its amust read document for anyone looking to work withcollections. 10. Performance Tips Enable GZIP compression Speed up the download of network-based resources byenabling GZIP compression on both your server and onyour client. The good news is that iOS already supports GZIPcompression by default if youre usingNSURLConnection, or a framework built on top of it suchas AFNetworking. There is a great article about GZIP compression whichexplains how to enable it on your Apache or IIS server. 11. Performance Tips Reuse and lazy Load Views Create your views as you need them. More views means more drawing; which ultimatelymeans more CPU and memory overhead. This isespecially true if your app embeds many views inside ofa UIScrollView. 12. Performance Tips Cache what matters Cache things that are unlikely to change, but areaccessed frequently. What can you cache? Some candidates for caching are remote server responses,images. NSURLConnection already caches resources on disk or inmemory according to the HTTP headers it processes. 13. Performance Tips Handle memory warnings iOS notifies all running apps when system memory isrunning low. UIKit provides several ways to receive these low-memorywarnings, including the following: Implement the applicationDidReceiveMemoryWarning: method of yourapp delegate. Override didReceiveMemoryWarning in your custom UIViewControllersubclass. Register to receive theUIApplicationDidReceiveMemoryWarningNotification notification. Upon receiving any of these warnings, free up any unnecessarymemory. Purge unused data structures, release any images that are notcurrently on-screen. 14. Performance Tips Reuse expensive Objects Some objects are very slow to initialize NSDateFormatter and NSCalendar are two examples. To avoid performance bottlenecks when working withthese objects, try to reuse these objects if at all possible. You can do this by either adding a property to your class orusing static 15. Performance Tips Optimize Your Table Views Tips for optimizing Table Views Reuse cells by setting the correct reuseIdentifier. Make as many views opaque as possible, including the cellitself. Avoid gradients, image scaling. If the cell shows content that comes from the web, be sure tomake those calls asynchronously and cache the responses. Reduce the number of subviews. Do as little work as possible in cellForRowAtIndexPath:. If youneed to do some work, do it only once and cache the results. Use the appropriate data structure to hold the information youneed. Different structures have different costs for differentoperations. 16. Performance Tips Speed up launch time Launching your app quickly is very important, especiallywhen the user launches for the first time. Firstimpressions mean a lot for an app! Ensure your app starts as quickly as possible is toperform asynchronous tasks. You need to strike a balance between what to fetch before applaunch and what to fetch once the app is launched. Try to avoid fat XIBs, since theyre loaded on the mainthread. But recall that storyboards dont have thisproblem so use them if you can! 17. Performance Tips Cache Images (when?) There are two common ways to load a UIImage from anapp bundle. Using imageNamed and second usingimageWithContentsOfFile. imageNamed has the advantage of caching the image as its loaded. Alternately, imageWithContentsOfFile simply loads the image with nocaching. When would you use one over the other? If youre loading a large image that will be used only once,theres no need to cache the image. However, imageNamed is a much better choice for images thatyoure going to be reusing in your app. 18. Performance Tips Reduce battery consumption Optimize use of the following features: The CPU Wi-Fi, Bluetooth, and baseband (EDGE, 3G) radios The Core Location framework The accelerometers The disk Consider the following guidelines: Avoid doing work that requires polling. Avoid accessing the disk too frequently. Do not draw to the screen faster than is needed. Connect to external network servers only when needed, and donot poll those servers. Disable location updates as soon as you can. 19. Performance Tips Reduce Apps memory footprint Actions to take Eliminate memory leaks. Make resource files as small as possible. Use Core Data or SQLite for large data sets. Load resources lazily. 20. Performance Tips Use NSLog as sparingly as possible in production Messages written using NSLog are presented in thedebugger console and even to the device's console login production. NSLog() takes a non-negligible amount of time. The following are commonly used log definitions thatare used to selectively perform NSLog() indebug/production:#ifdef DEBUG// Only log when attached to the debugger# define DLog(...) NSLog(__VA_ARGS__)#else# define DLog(...) /* */#endif// Always log, even in production#define ALog(...) NSLog(__VA_ARGS__) 21. Performance Tips Be Lazy Defer memory allocations until you actually need thememory. Defer reading the contents of a file until you actuallyneed the information. 22. Performance Tips Take Advantage of Perceived Performance The perception of performance is just as effective asactual performance in many cases. Many program tasks can be performed in thebackground, using a dispatch queue, or at idle time. Doing this keeps the applications main thread free to handleuser interactions and makes the program interface feel moreresponsive to the user. If your program needs to scan a number of files or performlengthy calculations, do so using a dispatch queue. There is a good document available on apples site forConcurrency Programing 23. Analyzing the performance Using apple tools for analyzing performance 24. ReferencesMarcelo Fabri - 25 iOS App Performance Tips & Tricks. Retrieved from