UICollectionView performance - _updateVisibleCellsNow

IosObjective CUicollectionview

Ios Problem Overview


I'm working on a custom UICollectionViewLayout that displays cells organized by day/week/month.

It is not scrolling smooth, and it looks like the lag is caused by [UICollectionView _updateVisibleCellsNow] being called on each rendering loop.

Performance is OK for < 30 items, but at around 100 or more, its terribly slow. Is this a limitation of UICollectionView and custom layouts, or am I not giving the view enough information to perform correctly?

Source here: https://github.com/oskarhagberg/calendarcollection

Layout: https://github.com/oskarhagberg/calendarcollection/blob/master/CalendarHeatMap/OHCalendarWeekLayout.m

Data source and delegate: https://github.com/oskarhagberg/calendarcollection/blob/master/CalendarHeatMap/OHCalendarView.m

Time Profile: Time profile - Custom layout

Update

Maybe its futile? Some testing with a plain UICollectionViewController with a UICollectionViewFlowLayout that is given approximately the same amount of cells/screen results in a similar time profile.

Time profile - Standard flow layout

I feel that it should be able to handle ~100 simple opaque cells at a time without the jitter. Am I wrong?

Ios Solutions


Solution 1 - Ios

Also don't forget to try to rasterize the layer of the cell:

cell.layer.shouldRasterize = YES;
cell.layer.rasterizationScale = [UIScreen mainScreen].scale;

I had 10 fps without that, and boom 55fps with! I'm not really familiar with GPU and compositing model, so what does it do exactly is not entirely clear to me, but basically it flatten the rendering of all subviews in only one bitmap (instead of one bitmap per subview?). Anyway I don't know if it has some cons, but it is dramatically faster!

Solution 2 - Ios

I have been doing considerable investigation of UICollectionView performance. The conclusion is simple. Performance for a large number of cells is poor.



EDIT: Apologies, just re-read your post, the number of cells you have should be OK (see the rest of my comment), so cell complexity may also be a problem.

If your design supports it check:

  1. Each cell is opaque.

  2. Cell content clips to bounds.

  3. Cell coordinate positions do not contain fractional values (e.g. always calculate to be whole pixels)

  4. Try to avoid overlapping cells.

  5. Try to avoid drop shadows.



The reason for this is actually quite simple. Many people don't understand this, but it is worth understanding: UIScrollViews do not employ Core Animation to scroll. My naive belief was that they involved some secret scrolling animation "sauce" and simply requested occasional updates from delegates every now and then to check status. But in fact scroll views are objects which don't directly apply any drawing behaviour at all. All they really are is a class which applies a mathematical function abstracting the coordinate placement of the UIViews they contain, so the Views coordinates are treated as relative to an abstract contentView plane rather than relative to the origin of the containing view. A scroll view will update the position of the abstract scrolling plane in accord with user input (e.g. swiping) and of course there is a physics algorithm as well which gives "momentumn" to the translated coordinate positions.

Now if you were to produce your own collection view layout object, in theory, you could produce one which 100% reverses the mathematical translation applied by the underlying scrollview. This would be interesting but useless, because it would then appear that the cells are not moving at all as you swipe. But I raise this possibility because it illustrates that the collection view layout object working with the collection view object itself does a very similar operation to the underlying scrollview. E.g. it simply provides an opportunity to apply an additional mathematical frame by frame translation of the attributes of the views to be displayed, and in the main this will be a translation simply of position attributes.

It is only when new cells are inserted or deleted moved or reloaded that CoreAnimation is involved at all; most usually by calling:

- (void)performBatchUpdates:(void (^)(void))updates
                 completion:(void (^)(BOOL finished))completion

UICollectionView requests cell layoutAttributes for each frame of scrolling and each visible view is laid out for each frame. UIView's are rich objects optimised for flexibility more than performance. Every time one is laid out, there are a number of tests the system does to check it's alpha, zIndex, subViews, clipping attributes etc. The list is long. These checks and any resulting changes to the view are being conducted for each collection view item for each frame.

To ensure good performance all frame by frame operations need to be completed within 17ms. [With the number of cells you have, that is simply not going to happen] bracketed this clause because I have re-read your post and I realise I had misread it. With the number of cells you have, there should not be a performance problem. I have personally found with a simplified test with vanilla cells, containing only a single cached image, the limit tested on an iPad 3 is about 784 onscreen cells before performance starts to drop below 50fps.

In practice you will need to keep it less than this.

Personally I'm using my own custom layout object and need higher performance than UICollectionView provides. Unfortunately I didn't run the simple test above until some way down the development path and I realised there are performance problems. I'm so I'm going to be reworking the open source back-port of UICollectionView, PSTCollectionView. I think there is a workaround that can be implemented so, just for general scrolling about, each cell item's layer is written using an operation which circumvents the layout of each UIView cell. This will work for me since I have my own layout object, and I know when layout is required and I have a neat trick that will allow the PSTCollectionView to fall back to its normal mode of operation at this time. I've checked the call sequence and it doesn't appear to be too complex, nor does it appear at all unfeasible. But for sure it is non-trivial and some further tests have to be done before I can confirm it will work.

Solution 3 - Ios

Some more observations that might be helpful:

I am able to reproduce the problem, using flow layout with around 175 items visible at once: it scrolls smoothly in the simulator but lags like hell on iPhone 5. Made sure they are opaque etc.

enter image description here

What ends up taking the most time seems to be work with a mutable NSDictionary inside _updateVisibleCellsNow. Both copying the dictionary, but also looking up items by key. The keys seems to be UICollectionViewItemKey and the [UICollectionViewItemKey isEqual:] method is the most time consuming method of all. UICollectionViewItemKey contains at least type, identifier and indexPath properties, and the contained property indexPath comparison [NSIndexPath isEqual:] takes the most time.

From that I'm guessing that the hash function of UICollectionViewItemKey might be lacking since isEqual: is called so often during dictionary lookup. Many of the items might be ending up with the same hash (or in the same hash bucket, not sure how NSDictionary works).

For some reason it is faster with all items in 1 section, compared to many sections with 7 items in each. Probably because it spends so much time in NSIndexPath isEqual and that is faster if the row diffs first, or perhaps that UICollectionViewItemKey gets a better hash.

Honestly it feels really weird that UICollectionView does that heavy dictionary work every scroll frame, as mentioned before each frame update needs to be <16ms to avoid lag. I wonder if that many dictionary lookups either is:

  • Really necessary for general UICollectionView operation
  • There to support some edge case rarely used and could be turned off for most layouts
  • Some unoptimized internal code that hasn't been fixed yet
  • Some mistake from our side

Hopefully we will see some improvement this summer during WWDC, or if someone else here can figure out how to fix it.

Solution 4 - Ios

Here is Altimac's answer converted to Swift 3:

cell.layer.shouldRasterize = true
cell.layer.rasterizationScale = UIScreen.main.scale

Also, it should be noted that this code goes in your collectionView delegate method for cellForItemAtIndexPath.

One more tip - to see an app's frames per second (FPS), open up Core Animation under Instruments (see screenshot).

enter image description here

Solution 5 - Ios

The issue isn't the number of cells you're displaying in the collection view total, it's the number of cells that are on screen at once. Since the cell size is very small (22x22), you have 154 cells visible on screen at once. Rendering each of these is what's slowing your interface down. You can prove this by increasing the cell size in your Storyboard and re-running the app.

Unfortunately, there's not much you can do. I'd recommend mitigating the problem by avoiding clipping to bounds and trying not to implement drawRect:, since it's slow.

Solution 6 - Ios

Big thumbs up to the two answers above! Here's one additional thing you can try: I've had big improvements in UICollectionView performance by disabling auto layout. While you will have to add some additional code to layout the cell interiors, custom code seems to be tremendously faster than auto layout.

Solution 7 - Ios

Beside the listed answers (rasterize, auto-layout, etc.), you may also want to check for other reasons that potentially drags down the performance.

In my case, each of my UICollectionViewCell contains another UICollectionView (with about 25 cells each). When each of the cell is loading, I call the inner UICollectionView.reloadData(), which significantly drags down the performance.

Then I put the reloadData inside the main UI queue, the issue is gone:

DispatchQueue.main.async {
    self.innerCollectionView.reloadData()
}

Carefully looking into reasons like these might help as well.

Solution 8 - Ios

In few cases it is due to Auto-layout in UICollectionViewCell. Turn it off (if you can live without it) and scrolling will become butter smooth :) It's an iOS issue, which they havnt resolved from ages.

Solution 9 - Ios

If you are implementing a grid layout you can work around this by using a single UICollectionViewCell for each row and add nested UIView's to the cell. I actually subclassed UICollectionViewCell and UICollectionReusableView and overrode the prepareForReuse method to remove all of the subviews. In collectionView:cellForItemAtIndexPath: I add in all of the subviews that originally were cells setting their frame to the x coordinate used in the original implementation, but adjusting it's y coordinate to be inside the cell. Using this method I was able to still use some of the niceties of the UICollectionView such as targetContentOffsetForProposedContentOffset:withScrollingVelocity: to align nicely on the top and left sides of a cell. I went from getting 4-6 FPS to a smooth 60 FPS.

Solution 10 - Ios

Thought I would quickly give my solution, as I faced a very similar issue - image-based UICollectionView.

In the project I was working in, I was fetching images via network, caching it locally on device, and then re-loading the cached image during scrolling.

My flaw was that I wasn't loading cached images in a background thread.

Once I did put my [UIImage imageWithContentsOfFile:imageLocation]; into a background thread (and then applied it to my imageView via my main thread), my FPS and scrolling was a whole lot better.

If you haven't tried it yet, definitely give a go.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOskarView Question on Stackoverflow
Solution 1 - IosAltimacView Answer on Stackoverflow
Solution 2 - IosTheBasicMindView Answer on Stackoverflow
Solution 3 - IosAndreas KarlssonView Answer on Stackoverflow
Solution 4 - IosGene LoparcoView Answer on Stackoverflow
Solution 5 - IosAsh FurrowView Answer on Stackoverflow
Solution 6 - IosNSSplendidView Answer on Stackoverflow
Solution 7 - IosRainCastView Answer on Stackoverflow
Solution 8 - IoscirronimboView Answer on Stackoverflow
Solution 9 - IosCWittyView Answer on Stackoverflow
Solution 10 - IosroycableView Answer on Stackoverflow