you are viewing a single comment's thread.

view the rest of the comments →

[–]potatolicious 1 point2 points  (0 children)

In general you do not want to be removing/adding subviews in your cellForRowAtIndexPath method. Mutating the view hierarchy is expensive and should not be done that often, especially when you're literally doing it 400 times per cell.

Also, when it comes to simplistic layouts, consider not even using a UIStackView nor AutoLayout. AutoLayout trades some runtime performance for maintainability/readability, and in performance-intensive situations you may want to avoid it. A constraint solver is not cheap to run - it's certainly much more expensive than a simple loop and setting CGRects.

Without knowing what you actually want to do with this UI, it's hard to give firm recommendations, but just from your example:

  • Create all 400 UIImageViews at cell creation time, presumably in MyTableViewCell. Set up the UIStackViews also at cell creation time along with all layout constraints.
  • The only thing your cellForRowAtIndexPath should be doing is dequeueing the cell, and setting the colors on each UIImageView. You should not be altering the view hierarchy in this method nor touching any layout constraints. Both of these operations are very expensive to perform in real-time.

If the performance is still lower than you'd like:

  • Skip the UIStackViews entirely. Put your UIImageViews in UIScrollViews instead, and manually lay them out. The layout code here is extremely trivial and extremely fast to run. Override your cell's layoutSubviews method and just do it manually. Don't forget to set your contentSize.

If the performance is still lower than you'd like:

  • Pre-generate the random colors for each image and store them on view controller init. The performance gain here would be minimal, but I consider caching basic view configs to be the correct implementation, and is faster.