statement: This article is translated from "IOS performance optimization", the original author Khang Vo. This article is purely for the purpose of technical exchange, does not have any commercial nature, and may not use this content for commercial profit. Welcome reprint, but hope to reprint the time Add source connection, thank you. Translator Contact information [email protected], if there are problems such as IOS development, welcome to discuss together, thank you. Another, because I have not much experience in translation, if the translation is inappropriate or not in place, I hope that all friends Haihan, can send a letter to the above mailbox, I will promptly according to your feedback, the translation of the manuscript to make timely changes, thank you!
A second example
When you run an application that contains TableView on an older device, each Cell
When a lot of sub-views (SubView) are made, customizing the Cell's drawing code will help improve performance. For IPhone4 and its previous devices, this performance optimization technique has the effect of making a significant difference.
In this example, I'm going to make the cell in the application more complex, with each cell having a total of 10 sub-views, including a variety of images, text, and so on. As a result, you'll see that the sliding performance of some real applications (like the Facebook app we're simulating) will be severely impacted by the complex sub-view structure of the Cell. I want to test the application interface as shown in 3-5.
Each Cell consists of a picture of a user's avatar, a user name, and a status that comes with a picture, title, and content. The test results are shown in table 3-5.
Table 3-6 shows the test results after customizing the Cell's drawing code
Comparing the data from table 3-5 and table 3-6, it can be seen that the personalized rendering code has a significant increase in rendering time. For an application with a complex sub-view structure, this performance is good enough to be done without optimization.
The Tableviewcell in Figure 3-6 has four images, plus a sub-view of a different background color. When you want to quickly and easily create a view component with a different background color in the existing view, the sub-view
A diagram is usually a good choice. But this approach may cause some performance problems when scrolling through the view, so you need to find a way to avoid this solution.
Now let's take a look at the source code for the new scenario, and in the new scenario, I'll personalize the Cell instead of using the sub-view scheme. Now you'll see how I've implemented this technology, and then I'll summarize the pros and cons of different technology options. The sample code originates from the engineering Drawingcellviewcontroller. The following is the main code snippet.
For Uitableviewcontroller:
-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) Indexpath {static NSString *cellidentifier = @ "Cellidentifier";
Customdrawingtableviewcell *cell = (Customdrawingtableviewcell *) [Self.tableviewdequeuereusablecellwithidentifier: Cellidentifier];
if (cell = = nil) {
cell = [[Customdrawingtableviewcell alloc]
Initwithstyle:uitableviewcellstyledefault Reuseidentifier:cellidentifier];}
[Cell Updatemycell];
return cell;
}
Well, as you can see, Uitableviewcontroller The main code is not much changed. The main difference between this code and the standard UITableViewCell Code is how you initialize the Cell.
[[Customdrawingtableviewcell alloc] Initwithstyle:uitableviewcellstyledefault reuseidentifier:cellidentifier];
Compare another section of code
[[UITableViewCell alloc] Initwithstyle:uitableviewcellstyledefault reuseidentifier:cellidentifier];
in a customized UITableViewCell (Customdrawingtableviewcell) in (ID) Initwithstyle: (Uitableviewcellstyle) style Reuseidentifier: (NSString
*) Reuseidentifier {
if (self = [super Initwithstyle:uitableviewcellstyledefault Reuseidentifier:reuseidentifier]) {
CGRect subFrame = CGRectMake (0.0, 0.0,
Self.contentView.bounds.size.width, Self.contentView.bounds.size.height);
Drawingview = [[Customdrawingview alloc] initwithframe:subframe];
Drawingview.autoresizingmask = Uiviewautoresizingflexiblewidth | Uiviewautoresizingflexibleheight;
[Self.contentview Addsubview:drawingview];return Self;
}
Next is the most important part: How to draw text, images, and controls within a view.
customdrawingview.m
-(void) DrawRect: (cgrect) Rect {
Self.backgroundcolor = [Uicolor Whitecolor];
Drawing code.
[Self.username Drawinrect:cgrectmake (70,0,) Withfont:usernamefont
Linebreakmode:uilinebreakmodetailtruncation Alignment:uibaselineadjustmentalignbaselines];
Drawing Image
[Self.avatarimage Drawinrect:cgrectmake (20, 5, 36, 34)];
Drawing button
[Self.button Drawinrect:cgrectmake (50, 5, 36, 34)];}
In short, the method of constructing a custom UITableViewCell in Uitableviewcontroller is similar to the previous one; you just need to decide if the element that pops up from the queue is empty, and if it is empty, construct a new element. In the initialization method of the new element, you must add a child view in the Cell. In this sub-view, you need to overwrite the DrawRect method and then use the Drawinrect method to draw the text or image.
The reason why a personalized drawing code can perform better than loading a nib file or adding a child view directly is because the GPU (graphics processor) will be responsible for running the personalized drawing code. The GPU renders and displays the UI very quickly, so the personalized drawing code draws only the best scenario with a complex sub-view structure.
[Note: Remember to set the background color of the customdrawingview to white. The default background color is black. ]
What can you learn from these examples? From the two examples listed above, you need to remember some basic knowledge.
(1) Use Reuseidentifier. This will improve your program's performance. (2) Try to reduce the Cell preparation time, especially when loading images from a network or file. This will show the picture in the shortest time possible.
(3) If your application's cell uses a large number of child view structures, you need to consider yourself drawing the cell manually through the code. This will allow the GPU to speed up the process.
[WARNING: Test results as you can see, FPS data is getting better, already approaching the ideal 60. However, if you use this approach, you cannot use Interfacebuilder to build your UI. You need to calculate the location of the drawing and put the information update into the drawrect. Soon, you'll
Finding maintenance programs becomes very difficult. Therefore, use the DrawRect method sparingly and avoid over-optimization. ]
Other Related technologies
On the TableView of rolling performance to optimize this topic, we have discussed some important
Technology. There are some tricks you don't use very often, but I'll introduce them here. If you can understand these concepts, you can use these techniques in other examples.
Cache height
Because TableView needs to know the height of the cell when creating a new cell, you need to cache that information. If the Cell's height is fixed, then you don't have to worry about this kind of thing. However, if those heights are not fixed, then you need to make sure that the cell height is computationally fast enough.
Try the following code:
-(CGFloat) TableView: (UITableView *) TableView Heightforrowatindexpath: (Nsindexpath *) indexpath{
return 80;}
Try to avoid the following code:
-(CGFloat) TableView: (UITableView *) TableView Heightforrowatindexpath: (Nsindexpath *) Indexpath {for (int i = 0; i < 100 ; i++) {
Find the smallest possible height for the row
}
return smallestheight; }
The first code is called multiple times when the operating system needs to render the cell or if the cell needs to be edited or reordered in the animation. But if you use the second piece of code, you need almost 100 calculations every time the operating system needs to know the height of the Cell.
Transparency
If possible, make all child views and layers of UITableViewCell as opaque as possible. When a view is transparent, IOS needs to draw two or more times on a single pixel, because that point belongs to multiple sub-views at the same time. The process of drawing is more time-consuming.
This setup can be done simply by Interfacebuilder. Developers should check the settings more than once to ensure that all sub-views are opaque, and figure 3-7 shows if the child view of the Cell is set to opaque.
For the corresponding code, we can also use the code to make the relevant settings, set the method as follows:
View.opaque = YES;
Avoid using graphic effects
Try to avoid effects like gradients in UIImage. After setting up the coreanimation, check the effects and related issues for your app, shown in 3-8 and 3-9.
Editing/Reflow Performance
In some of the previous chapters, I showed you how to draw directly, and in this way you can greatly optimize your application performance. This method of drawing can then cause some problems in terms of animation and the performance of Reflow.
When you use the Sub-view technique, the animation becomes faster, and UIKit does not need to redraw during the animation. Therefore, the relative processing speed becomes faster when using sub-view techniques rather than direct drawing techniques. If you use direct code drawing when you need to animate, you need to draw the associated view again two times to fit the new view. This will make the related work more complicated in terms of writing and maintaining the code.
Therefore, when optimizing the UITableView, it is necessary to weigh carefully. I recommend the use of sub-view techniques when there are not too many sub-view structures, or if you need to have related animation effects. After doing this, although the program may become slightly slower, the performance is good enough.
This chapter summarizes some of the performance optimization techniques you've learned by learning some examples and studying the relevant code.
(1) test with NSLog and coreanimation. With a real-life example, I've learned how to use these two tools to effectively test the relevant metrics to get a quick insight into the nature of the problem and how we've progressed after each step of optimization.
(2) proper reuse of Cell. This is the first and most important step in the performance optimization. This is easy to implement, but many applications do not. Therefore, if you have related performance issues, please check the relevant section to see if this optimization has been done.
(3) correctly cache, reuse images and data. Another important optimization step is to reduce the time it takes to load data and images when returning or displaying a Cell.
(4) Reduce the logical calculation time. Not only the I/O process slows down or blocks the UI thread, and any kind of data processing can have this effect. Therefore, you need to minimize this type of data processing.
(5) set to opaque. This small problem usually occurs when the developer adds elements to the view. If they do not set each view to a non-transparent state, the rendering will have to be rendered multiple times at the same point.
(6) cache the height. This is another small mistake that developers usually make. Whenever a new Cell is needed, there are two main methods to be called.
(7) Avoid using graphic effects. The more graphic effects you have on the Cell, the slower the rendering process will be. Therefore, you should also test this point. You should use Coreanimation to check the rendering of each UI component.
(8) Edit/reflow performance. Optimization of scrolling performance by using code-drawing techniques This approach poses some problems when editing cells or having cell-related animations. So the Uikit and animation frames have been optimized for child views. If your Cell is drawn by itself, the associated optimizations for these sub-views will be invalidated.