Performance issue when inserting sections into UIC

2019-09-07 09:41发布

问题:

Basically I'm using the default UICollectionViewFlowLayout. When I use insertSections it does take some time. Especially if the user scrolls this brings some stutters. I'm using auto layout where I position a label on my custom UICollectionViewCell. I'm dequeuing the cells and my supplementary views (header). Nothing special here.

Here is a screenshot of the Time Profiler:

What you can see here is that prepareLayout of UICollectionViewFlowLayout does consume a third of the available CPU power. Is there a possibility to speed this up? E.g. writing custom methods for layoutAttributesForElementsInRect:, layoutAttributesForItemAtIndexPath:, collectionViewContentSize, prepareLayout? How would this methods does look like?

Other observations I made:

The more often sections are added the longer performBatchUpdates with inserting the sections (about 420 items) does take. I'm adding everytime the same amount of items. I made some tests with Instruments. The CPU Usage goes over 100% when the stutter occur. Real memory usage is increasing but I ended my test with about 60 MB. About 48.000 cells were loaded in the dataset at that time (about 45 always on screen). Once the cells are loaded the scrolling works fluently (CPU about 100% max. but only short periods of time, user doesn't notice). The total bytes of allocations was about 1.6 GB in another test, but the persistent stayed low. The frames also drop to 0 if new sections are inserted.

I tried to go away from auto layout for the cell, use opaque background color for the cells, use clip to bounds for the cell, use shouldRasterize and so on. The cells don't overlap and no fractional values should be used (rounded width). I don't use shadows at all. I also tried to comment things out to see what has fault, but I think it must be something essential. I tested in simulator as well as on different devices.

Has anyone a clue how to increase the performance when inserting sections?

回答1:

There are quite a few unresolved symbols in the call tree of your image attachment. You could try to narrow down the performance problem in one of those call tree functions that consists of only the MonthView app.

Try to check Hide System Libraries and use Debug as a build configuration, so you can observe those symbols and navigate to a specific code within your app.

Once you are clear that your collection view data source or delegate doesn't contribute to the performance issues at the UICollectionView framework level, then you could spend your effort to find a way to minimize such collection view section updates.

Perhaps your cell auto layout configuration is quite complex, and you can probably simplify it?

Although it's hard to understand without actually looking at what your collection view cell is having.