UITableView optimization and uitableview Performance Optimization

Source: Internet
Author: User

UITableView optimization and uitableview Performance Optimization

 

As iOS developers, UITableView may be one of the most commonly used UI controls. Its importance is self-evident.

For TableView, I think the most important thing is the reuse mechanism of UITableViewCell.

Simply put, when TableView is rolled, tableView: cellForRowAtIndexPath: Is called. TableView only creates cells on the screen or a little more than the screen, when the new cell needs to be displayed for scrolling, TableView first puts the cell that has been removed from the screen into the cache pool, and then extracts the new cell from the cache pool for display, when the cache pool does not exist, a new cell is created. But cell may not be just one type. How can we identify the cell we need? Apple has done everything for us. We only need to set up an identifier. TableView can automatically reuse the corresponding cell from the cache pool based on identifier. This greatly saves the memory overhead.

After learning about the Reuse Principle of cell, let's take a look at the callback method of TableView. We know that TableView inherits from UIScrollView and must first determine its contentSize and position of each cell so that each cell can be correctly placed. Therefore, before creating or reusing a cell, tableView will call tableView: heightForRowAtIndexPath: To determine the contentSize and height of each cell, and then call tableView: cellForRowAtIndexPath: to display the corresponding cell. However, for those cells with hundreds or even hundreds of numbers, the computing height will consume a considerable amount of performance.

So first, let's look at how TableView is optimized around cell.


1. cell Reuse

This is very simple. Once registered, it will be automatically reused.

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    static NSString *Identifier = @"cell";    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];    if (!cell) {        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];    }        return cell;}

 

A lot of people will assign values to cells and bind data here. However, I recently read an article titled. We can bind data in tableView: willDisplayCell: forRowAtIndexPath.

2. cell Height Calculation

There are two types of cells. One is a fixed cell and the other is a dynamic cell.

A. fixed cell should adopt the following method:

Self. tableView. rowHeight = 88;

This method specifies that the height of all cells is 88 tableview, and the default value of rowHeight is 44. Therefore, an empty TableView is displayed as this. For a cell with a fixed height, the above method is used to specify the height without tableView: heightForRowAtIndexPath: to save unnecessary computing and overhead.

B. cell with dynamic height

We need to implement its proxy to give the height:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {    // return xxx}

 

After this method is provided, the above rowHeight settings will become invalid. In this method, we need to improve cell computing efficiency to save time.

It should be noted that since iOS8, the concept of self-sizing cell has been established, and cell can calculate its own height. However, companies on the market currently support iOS8 at the lowest level. It may take a long time to use this method.

In addition to improving the cell computing efficiency, we need to cache the calculated height. For the calculated height, there is no need to perform the second calculation.

In addition, this blog provides a good description of how to optimize cell height computing and when cell height is cached. We strongly recommend you read it in depth. Http://blog.sunnyxx.com/2015/05/17/cell-height-calculation/

3. Rendering

To ensure the smoothness of TableView, cell must be rendered quickly when sliding fast. Therefore, cell rendering must be fast. How can we improve cell rendering speed?

A. When there is an image, pre-render the image. First draw it in bitmap context, export it as a UIImage object, and then draw it to the screen, which greatly improves the rendering speed. For details, refer to: using pre-rendering to accelerate iOS image display

B. one of the best operations for rendering is the blending. Therefore, we do not need to use a transparent background, set the cell opaque value to Yes, do not use clearColor for the background color, and try not to use a shadow gradient.

C. Since the hybrid operation is executed using the GPU, we can use the CPU for rendering, so that the hybrid operation will not be executed. You can customize the drawing in the drawRect method of UIView, see: http://southpeak.github.io/blog/2015/12/20/perfect-smooth-scrolling-in-uitableviews/

4. Reduce the number of views

When we add system controls to cells, the system will actually call the underlying interface for plotting. When adding a large number of controls, it will consume a lot of resources and affect the rendering performance. When the default UITableViewCell is used and the control is added to its ContentView, the performance consumption is considerable. Therefore, the best method is to inherit UITableViewCell and override the drawRect method.

5. Reduce Unnecessary plotting

When implementing the drawRect method, its parameter rect is the area we need to draw. We do not need to draw areas outside the rect range, otherwise it will consume a considerable amount of resources.

6. Do not add a subView to the cell dynamically.

Add the cell during cell initialization, and set the hide attribute display and hide as needed.

7. asynchronous UI, do not block the main thread

We often see this phenomenon, that is, when the page is loaded, the whole page gets stuck, and it seems useless. The reason is that the main thread is blocked. Therefore, we can enable multi-threaded and asynchronous calls for loading network data requests or images.

8. Load the corresponding content as needed during slide

// Load as needed-if the difference between the target row and the current row exceeds the specified number of rows, load only three rows before and after the target scroll range.

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{    NSIndexPath *ip = [self indexPathForRowAtPoint:CGPointMake(0, targetContentOffset->y)];    NSIndexPath *cip = [[self indexPathsForVisibleRows] firstObject];    NSInteger skipCount = 8;    if (labs(cip.row-ip.row)>skipCount) {        NSArray *temp = [self indexPathsForRowsInRect:CGRectMake(0, targetContentOffset->y, self.width, self.height)];        NSMutableArray *arr = [NSMutableArray arrayWithArray:temp];        if (velocity.y<0) {            NSIndexPath *indexPath = [temp lastObject];            if (indexPath.row+33) {                [arr addObject:[NSIndexPath indexPathForRow:indexPath.row-3 inSection:0]];                [arr addObject:[NSIndexPath indexPathForRow:indexPath.row-2 inSection:0]];                [arr addObject:[NSIndexPath indexPathForRow:indexPath.row-1 inSection:0]];            }        }        [needLoadArr addObjectsFromArray:arr];    }}

 


Remember to add judgment in tableView: cellForRowAtIndexPath: method:

if (needLoadArr.count>0&&[needLoadArr indexOfObject:indexPath]==NSNotFound) {    [cell clear];    return;}

 

When moving fast, only the cells in the target range are loaded, which greatly improves smoothness.

Finally, there are still many aspects not mentioned about TableView optimization. I hope you can have more discussions ~

References

Https://medium.com/ios-os-x-development/perfect-smooth-scrolling-in-uitableviews-fd609d5275a5#.373u9fh4p

Http://blog.sunnyxx.com/2015/05/17/cell-height-calculation/

Http://southpeak.github.io/blog/2015/12/20/perfect-smooth-scrolling-in-uitableviews/

 

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.