25 Tips and tricks for enhancing the performance of iOS apps tips and tricks for application performance-intermediate intermediate articles

Source: Internet
Author: User
Tags sqlite database uikit

When developing an iOS application, it is critical that your program has good performance. This is also what users expect if your program is running slow or slow
Slow, will incur the user's bad comment.
However, due to the limitations of iOS devices, it is sometimes difficult to get good performance. In the development process, there are many things to remember and
And it's easy to forget about the performance impact.
That's why I'm writing this article! This article collects 25 tips and tricks that can improve program performance.
Directory directory
I've divided the performance optimization techniques into 3 different levels: Beginner, Intermediate, and advanced:
In performance optimization, when you encounter some complex problems, you should pay attention to and use the following techniques:
9. Reuse and lazy load view
10. Caching, caching, caching
11. Consider drawing
12. Handling Memory Warnings
13. Reuse of expensive objects
14. Using the sprite Sheets
15. Avoid data re-processing
16. Select the correct data format
17. Set the appropriate background image
18. Reduce the impact of Web content
19. Set the shadow Path
20. Optimize TableView
21. Choose the right data storage method
Intermediate performance boosts intermediate performance
Now, when you're doing code optimization, you've been able to perform some of the primary performance optimizations. But here are some other optimizations, although it may not be
Obviously (depending on the program's architecture and related code), however, if you can make the best use of these scenarios, their performance optimizations will be very clear
Explicitly 9) Reuse and lazy load view
More view is included in the program interface, which means more drawing tasks are needed when the interface is displayed, which means it consumes more
CPU and memory resources. In particular, a lot of view is added to a uiscrollview.
Management techniques for this situation can refer to the behavior of UITableView and Uicollect Ionview: Do not create all subview at once, but
Create a view when it is needed and add them to the reuse queue when the view is finished.
This allows the view to be configured only when the Uiscrollview is scrolled, thus avoiding the cost of assigning create view-which can be very
Consumption of resources.
Now there is the question of when the view that needs to be displayed in the program is created (for example, when a user taps a button, it needs to display a
View). There are two options available here:
1. Create a view when the screen is first loaded and hidden, and then display the view when needed.
2. The view is created and displayed until you need to display the view.
Each method has its own merits and determination.
Using the first method, you need to consume more content, because the created view always occupies memory until the view is released. However, to make
In this way, when the user taps the button, the program will quickly display the view, because only the visibility of the view needs to be modified.
Using the second method produces the opposite effect, and when needed, guesses the creation of the view, which consumes less memory, but when the user taps the button's
The view is not displayed immediately.
10) cache, cache, cache
When developing a program, an important rule is to "cache what's important"--these things don't change, and the frequency of access is high.
What can I cache to write? For example, the remote server response content, pictures, and even calculate the results, such as the UITableView line height.
Nsurlconnect ion based on the processing of HTTP headers, some resources have been cached to disk and memory. You can even manually create a
Nsurlrequest, let it load only the cached values.
The following code snippet is typically used to create a nsurlrequest for a picture:
1. + (Nsmutableurlrequest *) Imagerequestwithurl: (nsurl *) URL {
2. Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url];
4. Request. CachePolicy = Nsurlrequestreturncachedataelseload; This would make sure the
Request always returns the cached image
5. Request. Httpshouldhandlecookies = NO;
6. Request. httpshouldusepipelining = YES;
7. [Request addvalue:@ "image/*" forhttpheaderfield:@ "Accept"];
9. return request;
Note: You can use nsurlconnect ion to crawl a URL request, but you can also use afnetworking to crawl it without
Modify all network-related code-this is a trick! :] Consider drawing
If you want to get more information about HTTP caching, Nsurlcache, Nsurlconnect ion, and related content, then look at Nshipster
The Nsurlcache entry.
If you need to cache content that does not involve HTTP requests, then use Nscache.
The appearance and behavior of Nscache is similar to that of Nsdict ionary, but when the system needs to reclaim memory, Nscache automatically stores inside
Capacity. Mat T Thompson wrote a very good article about Nscache on Nshipster.
If you also want to know more about HTTP caching, it's recommended to read this article from Google:
Best-pract ICES document on HTTP caching.
11) Consider drawing
There are several ways to make beautiful buttons in iOS. Full-size images can be used to shrink
Or use Calayer, coregraphics, or even OpenGL to hand
Measuring and Drawing buttons.
Of course, the complexity of these methods is different, and the performance varies. Over here
A related article is worth reading: about the performance of graphics in iOS. which
Andy Matuschak, a former group member of Apple's Uikit team, wrote about the
Comments, there is a very good insight into the different approaches and their performance tradeoffs.
In short, using pre-rendered picture technology is the fastest, because iOS doesn't have to wait
Create graphics and draw shapes when they are displayed on the screen (the picture has been created
All right!). The problem with this is the need to put all the pictures in the program bundle
, which increases the size of the program. So using a scalable picture here will be lined up
Useful: You can remove the "wasted" space of the picture--ios can be reused. And
There is no need to create a different picture for different elements, such as buttons.
However, the use of the picture will lose the code to control the image, and then for different programs, you need to repeat the generation of each required picture,
and repeatedly placed in each program. This process is generally slower. The other point is if you need an animation, or a lot of pictures to go in
Minor adjustments (such as overlay of multiple colors), you need to add a number of images to the program, which increases the size of the program bundle.
In general, you need to consider what is most important: drawing performance or program size. Generally important, so in the same project,
Both should be considered.
12) Handling Memory warnings
When the system memory is low, iOS notifies all programs that are running. Apple's official documentation describes how to handle low memory warnings:
If your app receives this warning, it must free up as much memory as possible. The best by
Remove strong references to caches, image objects, and other data objects the can be recreated later. If the process
Low memory warning, you must release the memory as much as possible in the program. The best way to do this is to remove the cache involved in the strong reference, the picture object, and its
It can also be re-created after the data object is used.
The following methods are available in Uikit to receive low memory (low-memory) Warnings:
Implement the Applicat iondidreceivememorywarning: Method in App delegate.
Override the (override) Didreceivememorywarning method in the Uiviewcontroller subclass.
Register Uiapplicat iondidreceivememorywarningnot If ICAT io notifications in notification hubs.
Any unwanted memory needs to be released immediately upon receiving any of the above warnings.
For example, the default for Uiviewcontroller is to clear out the currently invisible view, and in the Uiviewcontroller subclass, you can clear some extra data. Images that are not displayed in the current screen in the program can also be removed.
When you receive a low memory warning, it is important to try to free up memory. Otherwise, the running program may be killed by the system.
However, be careful when clearing memory: Make sure that the objects that are purged can also be created. Also, when developing a program, use the
Test your program with the simulated memory warning feature in the iOS simulator!
13) Reuse of expensive objects
Some objects are very slow to initialize-such as Nsdateformat ter and Nscalendar.
However, it is sometimes possible to avoid using these objects, such as dates in parsing json/xml
To avoid performance bottlenecks when using these objects, you can try to reuse them as much as possible.
Object--Add a property to the class or create a static variable.
Note that if you use a static variable, the object will persist while the program is running,
Just like a single case.
The following code demonstrates creating a deferred-loading date format property. First Call Property
, a new date format is created. After the call is made, it will return to the created
Built-in instance object:
1.//in your. h or inside a class extension
2. @property (nonatomic, St Rong) nsdateformat ter *format ter;
4.//Inside the implementat ion (. m)
5./need, just use Self.format ter
6.-(Nsdateformat ter *) format ter {
7. if (! _format ter) {
8. _format ter = [[Nsdateformat ter alloc] init];
9. _format Ter.dateformat = @ "EEE MMM dd HH:mm:ss Z yyyy"; Twit ter date Format
One. return _format ter;
Also, remember to create a new Nsdateformat ter instance object when you set Nsdateformat ter's date format
As slow as it is! Therefore, it is very good to reuse Nsdateformat ter if the date format needs to be processed frequently in the program.
14) using Sprite Sheets
Are you a game developer? Yes, so the sprite sheets is the best choice. Using SP ri te she e ts
Select the correct data format
Are you a game developer? Yes, so the sprite sheets is the best choice.
One. Use sprite sheets to draw faster than usual drawing methods, and
and consumes less memory.
Here are two very good sprite sheets tutorials:
1. How to use animation and Sprite in Cocos2d Sheets
2. How to use texture packs (Texture Packer) and pixels in cocos2d
Format to create and optimize sprite Sheets
The second tutorial describes in detail the pixel format--the ability to measure performance in a game
If you are not familiar with sprite sheets, then you can look at the
Shaoxing: spritesheets– video, part 1and Part 2. The authors of these two videos are
Andreas Löw, who was the creator of the texture Pack (Texture Packer), was created by the texture pack
An important tool for building sprite sheets.
In addition to using sprite sheets, here are some of the things that are used in game development
Tricks, for example, if you have a lot of sprites (like shooting games), you can reuse sprites instead of creating sprites every time.
15) Avoid data re-processing
Many programs need to get data from a remote server to meet the needs of the program. This data is typically in JSON or XML format. In the request and receive
Data, it is important to use the same data structure.
Why is it? converting data into a program-appropriate data format in memory is an additional cost.
For example, if you need to display some data in table view, the data format that is requested and received is preferably in array format, which avoids a
Intermediate operations-converting data to a data structure that is appropriate for the program's use.
Similarly, if a program is accessing a specific value based on a key, it is best to request and receive a dictionary of key/value pairs.
The data obtained at the first time is the desired format and avoids the additional cost of converting the data into a program-friendly data format.
16) Select the correct data format
There are several ways to upload data from a program to a network server, where the data grid used
is basically JSON and XML. All you need to do is choose the correct number in the program.
Data format.
JSON is very fast to parse, and much smaller than XML, which means just
To transfer less data. And after iOS5, there are already built-in JSON deserialization
API, so it's easy to use JSON.
But XML also has its own advantage: if you use the Sax method to parse XML,
You can read XML edge parsing without waiting for all of the XML to get to the beginning of the solution.
This is different from JSON. When processing large amounts of data, this approach can improve
Performance, and reduce memory consumption.
17) Set the appropriate background image
In iOS encoding, like many other things, there are two ways to give the view
Set a background image: 1. You can use the Uicolor Colorwithpat Ternimge method to create a color and set the color to the background color of the view.
2. You can add a Uiimageview child view to the view.
If you have a full-size background picture, then you should use Uiimageview, because the Uicolor Colorwithpat Ternimge method is used to
Create a small picture-the image will be reused. Using Uiimageview at this time can save a lot of memory.
1.//could also achieve the same result in Interface Builder
2. UI ImageView *backgroundview = [[UI ImageView alloc] Initwithimage:[ui Image
imagenamed:@ "Background"];
3. [Self.view Addsubview:backgroundview];
However, if you plan to use small images as backgrounds, you should use the Uicolor Colorwithpat Ternimge method. In this case the drawing speed
will be fast, and will not consume a lot of memory.
1. Self.view.backgroundColor = [Uicolor colorwithpat ternimage:[ui Image
imagenamed:@ "Background"];
18) Reduce the impact of Web content
UIWebView is very useful. It makes it easy to display Web content and even to build content that uikit space is difficult to display.
However, you can be able to notice that the program uses UIWebView to assemble the SAF Ari program without Apple fast. This is because JIT compilation limits the
The use of the WebKit nitro engine.
So in order to get more performance, you need to adjust the size of the HTML. The first is to get rid of JavaScript as much as possible and avoid using large mines to build,
such as jquery. Sometimes it's faster to use the original JavaScript than the other frames.
Also, try to load JavaScript files asynchronously-especially when the page behavior is not directly affected, such as parsing the script.
Finally-make the images you use the same size as you actually need. As mentioned earlier, use sprite sheets as much as possible to save memory and
The speed of the lift.
For more information, you can check out:
WWDC Session #601 – Optimize UIWebView and Web content in the Web in iOS.
19) Set the shadow path
If you need to add a shadow to the view live layer, how do you handle it?
Most developers first add the Quartzcore framework to the project, and then add the following code: 1. #import < QUARTZCORE/QUARTZCORE.H>
3.//Somewhere later ...
4. UIView *view = [[UIView alloc] init];
6.//Setup the shadow ...
7. View.layer.shadowo?set = Cgsizemake ( -1.0f, 1.0f);
8. View.layer.shadowRadius = 5.0f;
9. view.layer.shadowOpacity = 0.6;
It looks very easy, doesn't it?
Unfortunately, however, there is a problem with this approach. Core Animat ion before rendering the shadow effect, it must be done by making an off screen (of
To determine the shape of the view, and this off-screen operation is very resource-intensive.
Here's a way to make the system more prone to shadow rendering: Set the shadow Path!
1. View.layer.shadowPath = [[Uibezierpath bezierPathWithRect:view.bounds] cgpath];
By setting the shadow path, iOS doesn't always have to calculate how the shadow is drawn. Just use your pre-calculated path. A little bad.
Is that, depending on the format of the view, it may be difficult to figure out the path. Another problem is that when the F Rame of a view changes, it must be updated every time
The bottom shadow path.
If you want to know more about it, Mark Pospesel wrote a great article: Shadowpath.
20) Optimize TableView
Table views require a fast scrolling-if not, the user will feel a pause.
To make Table view smooth scrolling, make sure that you follow the following recommendations:
Set the correct reuseident if er to reuse the cell.
Try to set the view to opaque, including the cell itself.
Avoid gradients, image scaling, and off-screen drawing.
If the row height is not the same, then cache it.
If the contents of the cell appear on this network, make sure that the content is obtained asynchronously.
Use Shadowpath to set the shadow.
Reduce the number of subview.
In Cellforrowat Indexpath: Try to do fewer operations. If you need to do some processing, then it is best to do it once and then the knot
Use the appropriate data structure to save the information you need. Different structures lead to different operating costs.
Use RowHeight, sect ionfooterheight and sect ionheaderheight to set a constant height without
obtained in delegate.
21) Choose the right data storage method to choose the right data storage method
21) Choose the right data storage method
How to choose storage when you need to store and read large amounts of data
The following options are available:
Using Nsuserdefaults for storage
Files saved in Xml,json or plist format
Archive with the Nscoding
Store to a local database, such as SQLite.
Use Core Data.
What's wrong with using nsuserdefaults? Although Nsuserdef Aults is good and easy, it is only for storing small amounts of data (such as your
level, or the sound is on or off). If you are storing large amounts of data, it is best to choose another storage method.
Storing large amounts of data as structured files can also pose problems. In general, you need to load all of the content into memory before parsing the structure data
, this is very resource-intensive. Although you can use Sax to work with XML files, this is a bit complicated. In addition, all objects that are loaded into memory are
Not necessarily all of them need to be used.
So what about using nscoding to save a lot of data? Because it is also read and write to the file, there is still a problem with that.
To save large amounts of data, it is best to use SQLite or core data. With SQLite or core data, you can make specific queries--just get
and load the required data objects--to avoid unreasonable searches of the data. In terms of performance, SQLite and core data do not have much difference.
The biggest difference between SQLite and core data is actually usage. Core data represents an object model, and SQLite is just a DBMS. One
, Apple recommends using core data, but you can use a low-level sqlite if you have a specific reason not to use core data.
In the program, if you choose to use SQLite, here is a handy library Fmdb: You can use the library to manipulate the SQLite database without deep use
25 Tips and tricks to enhance the performance of iOS apps-Beginner
25 Tips and tricks to enhance the performance of iOS apps-Advanced

25 Tips and tricks for enhancing the performance of iOS apps tips and tricks for application performance-intermediate intermediate articles

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.