-->

How expensive is UITableView's reloadData?

2020-07-14 06:21发布

问题:

I'm curious just how expensive in as far as resources go is UITableView's reloadData? I have an app which will make roughly 10 subsequent HTTP requests, and as it gets data / preps, it reloads the tableView. As the data set grows larger and larger, it's becoming very sluggish. I'm trying to figure out if it's because of the amount of times I'm reloading the tableView or because of how I'm grabbing/parsing the data.

What's the best practice in this case?

回答1:

The best practice is to have your implementation of cellForRowAtIndexPath: do as little work as possible. In fact, it really shouldn't be doing any work except populating the UITableViewCell instance with the data it needs to display.

You should be using cached UITableViewCells so you don't have to allocate a new cell each time. If you can do your parsing and such in a separate thread and make the parsed data, ready to present, accessible to cellForRowAtIndexPath:, you shouldn't have any performance problems.

You didn't say if you were using a custom UITableViewCell subclass, but if you are, deep view hierarchies can also present a performance problem, since each view in the hierarchy gets drawn. The flatter you can make UITableViewCells, the better.

Hope that gets you moving in the right direction.



回答2:

From UITableView.h:

 - (void)reloadData;                 // reloads everything from scratch. redisplays visible rows. because we only keep info about visible rows, this is cheap. will adjust offset if table shrinks

"This is cheap."

implement your table view methods well and it'll be no big deal to call this function all the time.

On a side note, you should try to use the appropriate methods to animate adding and removing rows if you are thinking of using reloadData for that.



回答3:

Best thing to do is profile your app to see where it is slow.

That said, if your table cells are all the same height, then I think

reloadData

only has to call

cellForRowAtIndexPath

for cells that are visible on screen.



回答4:

Table view reload expense is:

  1. Figuring out how many sections and rows per sections you have
  2. getting row heights.

Row heights in particular are figured out for all elements of the table, anytime you call reload data.

The remaining expense is cellForRowAtIndexPath, which is usually not too bad because it only is called for as many rows as are on the screen. It can be bad when scrolling if you do not reuse cells like you are supposed to.

The key for you is probably, to ask yourself what triggers the HTML load and possibly move that into a background thread.



回答5:

Boot To The Head is correct.

I'm doing a progressive one-by-one article list update in Instapaper, and I call -reloadData on each completed download. Sounds similar to what you're doing. It doesn't result in any noticeable performance slowdowns.